0% found this document useful (0 votes)
13 views

How To Create A Simple Calculator With JavaScript - Orangeable

Enter your email address: The document provides instructions on how to create a simple calculator using JavaScript, HTML, and CSS. It explains the HTML layout with buttons for numbers, operators, and other functions. It then covers the CSS styling to display the calculator and buttons. The main part is the JavaScript code which is explained last and gives the calculator its functionality by handling button clicks and performing calculations.

Uploaded by

fizanadeem253
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

How To Create A Simple Calculator With JavaScript - Orangeable

Enter your email address: The document provides instructions on how to create a simple calculator using JavaScript, HTML, and CSS. It explains the HTML layout with buttons for numbers, operators, and other functions. It then covers the CSS styling to display the calculator and buttons. The main part is the JavaScript code which is explained last and gives the calculator its functionality by handling button clicks and performing calculations.

Uploaded by

fizanadeem253
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable

How to Create a Simple Calculator with JavaScript


JavaScript

Subscribe
Enter your email address:

Subscribe Skip to Content


Back to Top

https://orangeable.com/javascript/calculator 1/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

In this tutorial, you'll learn the basics of creating a simple calculator with vanilla JavaScript,
orangeable
CSS, and HTML. My goal was to simplify and lessen the amount of code as much as possible
but is proven to be extremely useful and effective. Let's get right into the code!

The HTML
First, let's get the HTML for our calculator layout out of the way:

<div class="calculator">
<div class="output">0</div>

<div class="btn" data-type="operator" data-id="+">+</div>


<div class="btn" data-type="operator" data-id="-">−</div>
<div class="btn" data-type="operator" data-id="*">×</div>
<div class="btn" data-type="operator" data-id="/">÷</div>
<div class="btn" data-type="number" data-id="7">7</div>
<div class="btn" data-type="number" data-id="8">8</div> Subscribe
<div class="btn" data-type="number" data-id="9">9</div>
<div class="btn" data-type="equal" data-id="=" id="equal">=</div>Enter your email address:
<div class="btn" data-type="number" data-id="4">4</div>
<div class="btn" data-type="number" data-id="5">5</div>
<div class="btn" data-type="number" data-id="6">6</div>
<div class="btn" data-type="number" data-id="1">1</div>
<div class="btn" data-type="number" data-id="2">2</div> Skip to Content
<div class="btn" data-type="number" data-id="3">3</div>
<div class="btn" data-type="clear" data-id="C">C</div>
<div class="btn" data-type="number" data-id="0">0</div>
https://orangeable.com/javascript/calculator 2/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
<div class="btn" data-type="symbol" data-id=".">.</div>
</div>

This layout displays the overall calculator container along with the numeric display and
buttons, including the numbers, symbols, operations, etc.

Each of the buttons has two data attributes associated with them:

› data-id : The ID of the button, used to perform the calculations. I've included
this because some of the symbols used to perform the calculations are
different than their button text counterparts on computers versus how we're
used to seeing them in the real world. For example, × is * , ÷ is / , etc.

› data-type : The type of the button, used to determine what action should be
taken to update the display of the equation. This could include a numeric value,
operator, etc.
Subscribe
Enter your email address:
The CSS
The next part of our JavaScript calculator is the CSS code to style the calculator container
and buttons: Skip to Content

body {
https://orangeable.com/javascript/calculator 3/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
background-color: #15171d;
padding: 0px;
margin: 0px;
overflow: hidden;
}

div.calculator {
width: 100%;
font-family: "Arial", sans-serif;
max-width: 500px;
padding: 3%;
margin: 40px auto;
display: block;
}

div.output {
width: 94%;
background-color: #ddd;
font-size: 32px;
color: #333;
text-align: right;
padding: 5% 1.5%; Subscribe
margin: 1.5%;
float: left; Enter your email address:
}

div.btn {
width: 22%;
background-color: #555; Skip to Content
font-size: 20px;
color: white;
text-align: center;
https://orangeable.com/javascript/calculator 4/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable
g

orangeable padding: 5% 0px;


margin: 1.5%;
float: left;
cursor: pointer;
transition: 0.25s all ease-in-out;
-moz-transition: 0.25s all ease-in-out;
-webkit-transition: 0.25s all ease-in-out;
}

div.btn[data-type="operator"]
div.btn[data-type="symbol"] {
background-color: #333;
}

div.btn[data-type="equal"] {
background-color: #ce3078;
padding: 31.25% 0px;
float: right;
}

div.btn:hover {
opacity: 0.75; Subscribe
}
Enter your email address:
@media (max-width: 768px) {
div.btn[data-type="equal"] {
padding: 33.5% 0px;
}
}
Skip to Content

I'm not going to go into this too much because the primary focus is the JavaScript portion
https://orangeable.com/javascript/calculator 5/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable
I m not going to go into this too much because the primary focus is the JavaScript portion.
orangeable
So, to briefly explain this, we're stretching the output container across the entirety of the
calculator while each of the buttons is one-fourth the width of the calculator itself and styled
out in a grid format using float rules.

Each of the buttons has a transition speed of 250 milliseconds so hovering over each of the
buttons with a mouse enacts an animation. It just adds a cool effect and makes the
calculator feel more user-friendly overall.

Now that we've gone through the potatoes of the calculator, let's get into the meat!

The JavaScript
The true power of this calculator comes with the JavaScript code. First, let's create a set of
variables that we'll use in entirety of the example:
Subscribe
var output = document.getElementsByClassName("output")[0];
Enter your email address:
var equation = "";
var number = "";
var id = "";
var type = "";

Skip to Content

Here is a breakdown of each of the variables:


https://orangeable.com/javascript/calculator 6/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

› output : This variable is the display of our JavaScript calculator that shows the
orangeable
most current input or output depending on the button sequence clicked. It's a
pointer to the HTML element with class name output so we don't have to
continually point to it again later on.

› equation : This variable stores all of the user input, which we will evaluate each
time an operator button is clicked or the equal = button is clicked.

› number : This variable stores the digits and decimals input by the user and is
used for display purposes only. When you select a set of digits or a decimal, it
will display until an operator is selected or the equal = button is clicked, then it
resets again as more digits are selected. Doing so keeps the display cleaned up
and easy to read.

› id : This variable stores the ID attribute of the button clicked.

› type : This variable stores the type attribute of the button clicked. Subscribe
Next, we'll create event handlers for each of the JavaScript calculator Enter yourWhen
buttons. email address:
a
button is clicked, the id and type variables are assigned using the button attribute values
so we can determine how to format our equation.
Skip to Content
var buttons = document.getElementsByClassName("btn");

for (var i = 0; i < buttons.length; i++) {


https://orangeable.com/javascript/calculator 7/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable
buttons[i].addEventListener("click", function() {
orangeable id = this.getAttribute("data-id");
type = this.getAttribute("data-type");

switch (type) {
case "clear":
Clear();
break;

case "operator":
Operator();
break;

case "symbol":
Symbol();
break;

case "equal":
Equal();
break;

default:
Default();
Subscribe
break; Enter your email address:
}
}, false);
}

Skip to Content
Each of the type attributes determines which action will be performed, or which function call
will be made.
https://orangeable.com/javascript/calculator 8/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
The Clear() Method
The Clear() method clears the latest user input and the equation, and resets the output
display to 0:

function Clear() {
number = "";
equation = "";
output.innerHTML = 0;
}

The Operator() Method


Subscribe
The Operator() method appends the selected operator to the end ofEnter the equation
your email and
address:
updates the calculator's display. The number variable is also reset to keep the calculator
display clean like previously explained:

function Operator() { Skip to Content


equation += id;
output.innerHTML = number + " " + id;
number = "";
https://orangeable.com/javascript/calculator 9/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
}

The Symbol() Method


The Symbol() method is only used to append a decimal point to the user-input number:

function Symbol() {
number += id;
equation += id;
output.innerHTML = number;
}

The Equal() Method Subscribe


Enter your email address:
The Equal() method evaluates the entire equation up to this point and displays the answer
to the screen. The user can continue to add more to the equation by selecting additional
operators and numbers:
Skip to Content
function Equal() {
number = eval(equation);
equation = number;
https://orangeable.com/javascript/calculator 10/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable
q ;

orangeable
}
output.innerHTML = number;

The Default() Method


The Default() method handles all numeric button click events by the user and updates the
equation and display accordingly:

function Default() {
number += id;
equation += id;
output.innerHTML = number;
}

Subscribe
Keyboard Input Enter your email address:

The last piece of this JavaScript calculator example is an event handler to handle user input
with a keyboard. When I use a calculator on a computer, I generally use the keyboard to type
out the equation versus clicking each button individually, so I thought it would be useful Skip
to to Content
include in this tutorial:

https://orangeable.com/javascript/calculator 11/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
document.addEventListener("keyup", function(event) {
if (event.keyCode != 13) {
for (var i = 0; i < buttons.length; i++) {
var id = buttons[i].getAttribute("data-id");

if (id == event.key) {
buttons[i].click();
}
}
}
else {
document.getElementById("equal").click();
}
}, false);

A keyup event handler is added to the document object, with a for loop that matches the
user input from the keyboard to any of the existing buttons on the calculator. If one of the
buttons exists, then it triggers a button click event on the selected button. If the Enter
button is pressed on the keyboard, then the equal = button on the calculatorSubscribe
is clicked,
solving the equation.
Enter your email address:

Conclusion
Skip to Content
This JavaScript calculator tutorial is pretty basic but packs a punch with the amount of
functionality offered and such a little amount of code.
https://orangeable.com/javascript/calculator 12/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
You can download, clone, or fork the full code example from the GitHub repository and
update or use it to your liking. Enjoy!

Last Updated: January 09, 2022


Created: December 17, 2021

Share this:

Subscribe & Learn More!


Enter your email address:

Subscribe
Subscribe
Enter your email address:

Comments Skip to Content

There are no comments yet. Start the conversation!


https://orangeable.com/javascript/calculator 13/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
Add A Comment
Name

Email address

Write a comment here

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not
post spam, keep the conversation constructive, and be nice to each other. Subscribe
Enter your email address:
Post Comment

Subscribe to the newsletter to receive updates on new tutorials


Remember my info Skip to Content

https://orangeable.com/javascript/calculator 14/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
More JavaScript

The 7 JavaScript Data Types with Examples


Get the Client's Timezone & Offset in JavaScript
Create A 2D Tile-Based Game with JavaScript
view all

Subscribe
to receive more tutorials
straight to your inbox! Subscribe
Enter your email address:

Skip to Content

https://orangeable.com/javascript/calculator 15/16
8/30/23, 1:02 AM How to Create a Simple Calculator with JavaScript - Orangeable

orangeable
Advertising Disclosure: I am compensated for
purchases made through affiliate links. Click
here for details.

About | Contact | Privacy | Accessibility


Orangeable - Copyright © 2023

Subscribe
Enter your email address:

https://orangeable.com/javascript/calculator 16/16

You might also like