search
HomeWeb Front-endJS TutorialCreating a Basic Calculator Using HTML, CSS and JavaScript

Creating a functional calculator in JavaScript is fun and there are a lots of concept used such as DOM Manipulation, Event Handling, Conditional Logic, String Manipulation, Arithmetic Operations, Keyboard Input Integration and CSS Styling for user interface. In this blog post, we'll dive deep into the code, breaking down each line to understand its properties and functionality. By the end of this blog, we will have a solid grasp of how the calculator works.

Lets get started.

Setting Up the HTML Structure

The HTML is straight forward, starting with a standard boilerplate. below is the code snippet for index.html

Creating a Basic Calculator Using HTML, CSS and JavaScript

The

sections, each containing a set of buttons. These sections include digits (0-9), mathematical operators ( , -, *, /), and other essential buttons such as AC, C, %, =, and ..

The tag links to an external JavaScript file, script.js, where the logic and functionality of the calculator are defined. This external file handles the user interactions and calculations, enabling the calculator to perform operations as intended.

Here, The display-box shows the input and displays the result while the button-box holds all the calculator buttons.

Adding CSS for Styling

Now, let's style our calculator to make it visually appealing and user-friendly.

Creating a Basic Calculator Using HTML, CSS and JavaScript

Lets breakdown the css code.

  1. Wrapper Styling

Creating a Basic Calculator Using HTML, CSS and JavaScript

The min-height: 100vh; ensures the wrapper occupies at least the full height of the viewport. The display: flex; enables a flexible layout, allowing alignment of its children. The justify-content: center; centers the content horizontally, while align-items: center; centers the content vertically. Lastly, the border: 2px solid black; adds a border around the wrapper.

  1. Calculator Container Styling:

Creating a Basic Calculator Using HTML, CSS and JavaScript

The display: flex; makes the calculator container flexible, allowing child elements to be laid out in a row or column. The flex-direction: column; arranges the child elements vertically. The gap: 12px; adds spacing between each section or element. Finally, width: 500px; sets the width of the calculator to 500px.

  1. Display Box Styling

Creating a Basic Calculator Using HTML, CSS and JavaScript

The border: 1px solid black; adds a border to the display box. The padding: 16px; provides space inside the box for better readability. The text-align: right; ensures the text is aligned to the right. The font-size: 24px; increases the font size for improved visibility, while border-radius: 5px; rounds the corners of the box.

  1. Buttons Container and Buttons Styling

Creating a Basic Calculator Using HTML, CSS and JavaScript

Here, the buttons container is styled with .flex-container, where display: flex; creates a flexible layout for its child elements. The justify-content: space-between; property evenly distributes the buttons with space between them, while gap: 8px; ensures proper spacing between each button for better alignment.

Each button is styled with flex: 1;, which makes them take up equal space within a row. Padding: 16px; adds space inside each button for comfort, and font-size: 20px; ensures the text is readable. The font-weight: bold; makes the text stand out, whileborder: 1px solid black; adds a border around each button. Additionally, border-radius: 8px; slightly rounds the corners of the buttons, and cursor: pointer; changes the cursor to a pointer when hovered over. The background color of the buttons is set to white with background-color: rgb(255, 255, 255);.

For the "=" button, the .equal class uses flex: 2.5; to give it more space, making it 2.5 times the width of the other buttons. When the button is hovered over, the button:hover style changes the background color to grey, background color:rgb(127, 131, 131); and the text color to white. This transition effect is smoothed by transition: background-color 0.3s ease, color 0.3s ease;, which allows for a 0.3-second fade between the colors.

With above HTML and CSS, our Calculator looks like this:

Creating a Basic Calculator Using HTML, CSS and JavaScript

Now lets dive into the main part, giving life to our calculator.
JavaScript Code Snippet
Creating a Basic Calculator Using HTML, CSS and JavaScript

Lets break down the code for better understanding.

  1. Selecting DOM Elements

Creating a Basic Calculator Using HTML, CSS and JavaScript

The displayBox variable holds a reference to the display box (

  1. Variables for Display and Operators

Creating a Basic Calculator Using HTML, CSS and JavaScript

The displayValue variable holds the current value to be shown on the screen, ensuring accurate updates during calculations. The lastOperator variable keeps track of the last operator used, preventing errors such as consecutive operator inputs. Additionally, console.log is utilized for debugging purposes, specifically to log the calculatorBtns node list for review.

  1. Button Click Event Listener/Looping Over Each Buttons

Creating a Basic Calculator Using HTML, CSS and JavaScript

The forEach method is used to loop through each button in the calculatorBtns collection. For each button, the innerText property is assigned to the buttonValue variable, which holds the text displayed on the button, such as "AC", "C", "9", " ", etc.

An onclick event listener is then added to each button. When a button is clicked, the assigned function is executed. This function, handleButtonAction(buttonValue), takes the button's text (buttonValue) as an argument. By passing the button's value, the function allows the calculator to perform the correct action, such as clearing the display, inputting a number, or performing a mathematical operation.

  1. Handling Key-press for Keyboard Input

Creating a Basic Calculator Using HTML, CSS and JavaScript

This allows the calculator to also work with the keyboard. When a key is pressed, the corresponding button's action is triggered. For example, pressing "1" on the keyboard will trigger the handleButtonAction() function with the value "1".

  1. Display Function

Creating a Basic Calculator Using HTML, CSS and JavaScript

The display() function updates the content of the display box (displayBox) with the current displayValue. If displayValue is empty, it shows "0.0" by default.

  1. Button Action Handler(Main Logic):

Creating a Basic Calculator Using HTML, CSS and JavaScript

The code performs several steps to update the calculator's display and handle the calculation. First, eval(displayValue) evaluates the mathematical expression stored in the displayValue. For example, if the display shows "3 5", eval calculates and returns the result, which in this case would be 8.

Next, displayValue = String(result) converts the result into a string and updates the displayValue to show the result on the screen. Once the calculation is complete, lastOperator = "" resets the lastOperator to an empty string, ensuring that any previous operator is cleared. Finally, the display() function updates the display to show the result of the calculation.

  1. AC(All Clear) and C (Clear) Button Logic

Creating a Basic Calculator Using HTML, CSS and JavaScript

When the "AC" button is clicked, the code checks if buttonValue is equal to "AC". If true, it resets the displayValue to an empty string, effectively clearing the entire display and resetting the calculator. The display() function is then called to update the display with the empty value.

For the "C" button, if buttonValue is "C", the code removes the last character from displayValue using slice(0, -1). This allows the user to delete the last input or character, and the display() function is called again to update the display accordingly.

  1. Validating Operators

Creating a Basic Calculator Using HTML, CSS and JavaScript

This condition is used to validate if an operator can be pressed based on the current value displayed.

The condition ["%", "/", "*", " "].includes(buttonValue) checks if the button clicked is one of the operators (%, /, *, ). If the button is an operator, the next check if (!displayValue || displayValue === "-") ensures that the operator cannot be pressed if the display is empty or only contains a minus sign (-). This prevents errors such as having two consecutive operators or starting with an operator. If the condition is true, the function simply returns and no operator is added to the display.

  1. Prevent Consecutive Operators

Creating a Basic Calculator Using HTML, CSS and JavaScript

This block of code handles the scenario where consecutive operators are pressed, preventing invalid input such as " " or " -."

First, if (["%", "/", "*", " ", "-"].includes(buttonValue)) checks if the button clicked is an operator. Then, const lastCharacter = displayValue.slice(-1) retrieves the last character of the current expression in displayValue.

Next, the lastOperator = buttonValue updates the lastOperator variable to store the current operator. If the last character is also an operator, as checked by if (["%", "/", "*", " ", "-"].includes(lastCharacter)), the code removes it using displayValue.slice(0, -1). This ensures that only one operator appears at the end of the expression and prevents consecutive operators from being added.

  1. Validating Decimal Points

Creating a Basic Calculator Using HTML, CSS and JavaScript

This block of code ensures that a decimal point (.) can only appear once within a number, preventing invalid inputs like "3..5."

First, the condition if (buttonValue === ".") checks if the button clicked is a decimal point. If so, it proceeds with the validation.

Next, const lastOperatorIndex = displayValue.lastIndexOf(lastOperator) finds the position of the last operator in the displayValue. Then, const currentNumberSet = displayValue.slice(lastOperatorIndex) || displayValue extracts the portion of displayValue after the last operator, which represents the current number being entered. If there is no operator, the entire displayValue is considered.

Finally, if (currentNumberSet.includes(".")) checks if the extracted number portion already contains a decimal point. If it does, the function returns early, preventing the user from entering a second decimal point. This ensures that numbers like "3.5" are valid, but inputs like "3..5" are not.

  1. Update the Display with New Value:

Creating a Basic Calculator Using HTML, CSS and JavaScript

The code displayValue = displayValue buttonValue; appends the value of the pressed button (such as a number or operator) to the existing displayValue string. This builds the current expression or number as the user interacts with the calculator.

After appending the button value, the display() function is called to update the display, ensuring it reflects the updated displayValue. This ensures that the user sees the most current value or expression as they enter it.

Conclusion

This JavaScript code handles the logic for displaying values, performing calculations, clearing inputs, and validating expressions in a calculator. It works with both button clicks and keyboard input. The key features include performing calculations when the "=" or "Enter" keys are pressed, handling the AC (all-clear) and C (clear last character) buttons, and preventing invalid operations such as consecutive operators or multiple decimal points. Additionally, the display is updated after each action, ensuring that the user sees the most current value or expression. Together, these features provide the foundation for a functional and interactive calculator.

Below are my demo links so feel free to check out the full code, clone the repository, or interact with the live demo. Happy coding!
GITHUB - [https://github.com/bigyan1997/calculator]
VERCEL - [https://calculator-delta-sepia-91.vercel.app/]

The above is the detailed content of Creating a Basic Calculator Using HTML, CSS and JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft