Have you ever solved an equation on a calculator and wondered how to code the calculator as a program? Well you’re in just the right place as we’ll be coding exactly that! Before we get started, let’s brush up on the language we’ll incorporate into our calculator program today. Learn HTML, CSS, and JavaScript from scratch here.
HTML stands for Hyper Text Markup Language. It’s a beginner-friendly language that one can use to build the content or structure of a website. HTML creates static content that is visible on the website.
Here's a beginner-friendly HTML tutorial to build your concepts!
CSS stands for Cascading Style Sheets. It builds on top of HTML by providing an efficient set of ways to both format and style the content. With the help of CSS, we can completely transform plain content, create various layouts, set colors and shades, align material, and much more.
Revise your concepts on CSS text, color, and fonts now!
JavaScript is the actual programming language in use here. It holds the power to change the behavior of content dynamically and deal with user input.
We’ll be using these three languages to create a basic calculator that gives accurate results and is nicely styled too. By the end of this blog, we’ll be able to create a working calculator like the one below, so without further ado, let’s get started!
We’ll begin by giving our calculator website a name called “Educative’s Calculator” within the <title>
tag.
<title>Educatives Calculator</title>
Let’s link our stylesheet “styles.css” to the main HTML file.
<link rel="stylesheet" href="styles.css">
Since we will use JQuery, a highly used JavaScript library for updating the web page, do not forget to include the link to JQuery so that it can be incorporated into our code too.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This is where the actual fun begins! The “calculator” div holds the heading of the calculator as well as both the numbers and the result that will be shown on the screen. This is accomplished by creating three sub divs, named “main-heading”, “one-nine”, and “result”, respectively.
The “one-nine” div further consists of a div named “input-div” and 15 buttons.
Our input div consists of a paragraph <p>
tag that is initially kept empty and is populated with the input of the user as they start to press the buttons.
<div class="input-div"><p class = "input"></p></div>
The buttons of the calculator are created using the <button>
tag and they are given their own class names to help in positioning or styling them using our stylesheet. Our buttons include the numbers from 0 to 9, a clear button (C) that empties the input, an equal (=) button that shows the result, the division sign (/), the multiplication sign (*), the addition sign (+), the subtraction sign (-), and finally the decimal (.) sign.
<button class="num-btn clear">C</button><button class="num-btn equal">=</button><button class="num-btn decimal">.</button><button class="num-btn plus">+</button><button class="num-btn seven">7</button><button class="num-btn eight">8</button><button class="num-btn nine">9</button><button class="num-btn minus">-</button><button class="num-btn four">4</button><button class="num-btn five">5</button><button class="num-btn six">6</button><button class="num-btn divide">/</button><button class="num-btn one">1</button><button class="num-btn two">2</button><button class="num-btn three">3</button><button class="num-btn multiply">*</button>
Having completed both our buttons and the input displayer, we can finally add a variable that depicts the final result of the calculator. Like the input, it’s also initially kept empty and is updated whenever a calculation is made.
<div class="result"><h2>Result = </h2></div>
The stylesheet below accomplishes the following:
Applies a maroon and black theme for the calculator.
Arranges the content using flex and grid.
Styles each button (i.e. the size, border, and more).
Causes a change in color, once a button is hovered over, for a superior user experience.
Reduces the size of the calculator below a certain width using a media query.
body{background-color: black;color:white;}.one-nine{display: grid;grid-template-columns: 1fr 1fr 1fr 1fr;}.calculator{display:flex;flex-direction: column;justify-content: center;align-items: center;width: 100vw;height: 100vh;}.num-btn{padding:3rem;border:none;font-size: larger;border: 1px solid gray;background-color: rgb(41, 3, 3);color:white;}.num-btn:hover{background-color: maroon;color: white;}.input-div{grid-column: span 4;padding-right: 1rem;padding-bottom: 1rem;border: 2px solid gray;font-size: larger;height: 5rem;}.input{width: 100%;height: 100%;padding: 0px;margin: 0px;display: flex;flex-direction: row;justify-content: flex-end;align-items: flex-end;}@media only screen and (max-width:800px){.num-btn{padding:2rem;border:none;font-size: medium;border: 1px solid gray;background-color: rgb(41, 3, 3);color:white;}}
JQuery makes updating values or defining actions a hassle-free process. We can add our JavaScript to the HTML file by simply wrapping the code in the <script>
tag.
The whole script becomes eligible to run once the document has loaded; therefore, the functionality is defined in the ready function.
$(document).ready(function(){var expression = '';
First and foremost, let’s code up the function for clearing the input and output.
The HTML tag with the class input is selected and its text is initialised to an empty string.
The expression i.e. the query that the user wants the answer for, is also initialised to an empty string.
The result of the expression is kept empty too and is added to a <h2>
tag for better visibility once the expression is calculated.
$('.clear').click(function(){$('.input').text('');expression = '';result = '';$('h2').text("Result = " + result);});
Second, whenever the user clicks on a number or the decimal point, the value is appended to the expression and is displayed above the buttons by altering the input text as well.
$('.one, .two, .three, .four, .five, .six, .seven, .eight, .nine, .decimal').click(function(){expression += $(this).text();$('.input').text(expression);});
Similarly, the same functionality is achieved for the various mathematical operators.
$('.multiply, .divide, .minus, .plus').click(function(){expression += $(this).text();$('.input').text(expression);});
Once we have completed the input expression, we are now ready to calculate the answer for it.
We save the final expression by selecting the content in the input.
We use the eval(expression)
method, which is a built-in JavaScript function to calculate strings of mathematical expressions and save the answer in the variable result
.
The result is displayed on the screen by setting the text of the <h2>
tag, which was responsible for displaying the answer.
In case the input is not valid or can not be computed on, an alert will be displayed on the screen, saying “Invalid expression”.
$('.equal').click(function(){expression = $('.input').text();try {var result = eval(expression);$('h2').text("Result = " + result);} catch (error) {alert('Invalid expression');}});
Congratulations, we have finally created a calculator using only HTML, CSS, and JavaScript. Let’s take a look at various input values and see how the code works for each.
Our first example uses multiple operators and numbers for the calculation.
Our second example depicts the usage of decimal points as well.
The following widget shows the live working for our HTML CSS JavaScript calculator. Feel free to edit the code and experiment with the results!
Now that you are a pro at using HTML CSS and JavaScript for making calculators, try answering the following question below to test your knowledge!
Try to answer it yourself!
What does the document.ready() function do?
Free Resources