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
The
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.
Lets breakdown the css code.
- Wrapper Styling
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.
- Calculator Container Styling:
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.
- Display Box Styling
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.
- Buttons Container and Buttons Styling
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:
Now lets dive into the main part, giving life to our calculator.
JavaScript Code Snippet
Lets break down the code for better understanding.
- Selecting DOM Elements
The displayBox variable holds a reference to the display box (
- Variables for Display and Operators
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.
- Button Click Event Listener/Looping Over Each Buttons
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.
- Handling Key-press for Keyboard Input
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".
- Display Function
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.
- Button Action Handler(Main Logic):
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.
- AC(All Clear) and C (Clear) Button Logic
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.
- Validating Operators
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.
- Prevent Consecutive Operators
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.
- Validating Decimal Points
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.
- Update the Display with New Value:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

To write clean and maintainable JavaScript code, the following four points should be followed: 1. Use clear and consistent naming specifications, variable names are used with nouns such as count, function names are started with verbs such as fetchData(), and class names are used with PascalCase such as UserProfile; 2. Avoid excessively long functions and side effects, each function only does one thing, such as splitting update user information into formatUser, saveUser and renderUser; 3. Use modularity and componentization reasonably, such as splitting the page into UserProfile, UserStats and other widgets in React; 4. Write comments and documents until the time, focusing on explaining the key logic and algorithm selection

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.
