Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Build a Calculator using JavaScript, HTML, and CSS in 2025

Updated on 07 December, 2024

27.24K+ views
13 min read

Building a calculator using HTML, CSS, and JavaScript is a great way to learn the basics of web development while creating a practical tool. In this tutorial, we will walk through the process of building a functional calculator from scratch, using modern web technologies for the year 2025

We’ll explore how to create the structure with HTML, style the user interface with CSS, and implement the logic with JavaScript. This project will give you hands-on experience with handling user input, performing calculations, and designing a clean, responsive layout.

Key Technologies Used:

  • HTML: For structuring the calculator layout.
  • CSS: For styling and making the calculator responsive.
  • JavaScript: For implementing calculator logic and interactivity.

By the end of this guide , you’ll have a fully functional calculator using JavaScript that can perform basic arithmetic operations. Whether you're just starting out or looking to enhance your skills, this project is an excellent way to dive into calculator development using HTML, CSS, and JavaScript.

Step-By-Step Process to Build a Calculator

Before directly going to code in HTML, CSS, and Java, let’s plan, how to build a calculator. It helps define the features, layout, and user experience, ensuring the project is organized and functional. Let’s break down the planning process into two key areas: features and functionality and wireframing and layout design.

Features and Functionality

The first step in planning the calculator is deciding on the core features. Here are the primary functionalities we need to implement for a calculator using JavaScript:

  • Basic Arithmetic Operations: The calculator should handle the four basic operations: addition, subtraction, multiplication, and division.
  • Clear Button (C): A button to reset the display and clear any input.
  • Backspace (←): A button to remove the last character entered, allowing users to correct mistakes.
  • Decimal Point (.): Support for floating-point numbers, enabling decimal calculations.
  • Equals (=): A button to evaluate the current expression and display the result.
  • Responsive Design: The layout should be flexible, working well on both desktop and mobile devices.
  • Error Handling: The calculator must manage invalid inputs (e.g., division by zero) and provide appropriate error messages.

These features will give us a fully functional calculator that meets the needs of most users. Once the features are defined, it’s important to design how the calculator will look and how users will interact with it.

Wireframing and Layout Design

Wireframing involves planning the arrangement of elements like buttons and the display screen. The layout of the calculator should be intuitive and easy to use. Typically, the number buttons (0–9) are placed in a grid, with operators and special buttons like C (clear),  (backspace), and = (equals) positioned logically for ease of use. 

The display should be large enough to show input clearly and should sit at the top for easy visibility. Additionally, the layout should be responsive, ensuring the calculator works well on all screen sizes, especially mobile devices.

Step 1. Setting Up the Project

To begin building a calculator using HTML, CSS, and JavaScript, we need to set up the project structure. This will help keep everything organized and ensure that all components of our calculator function properly together.

Check out Java Free Online Course

 Here’s how to structure your project and link the necessary files.

1. Folder Structure

For a clean and manageable project, use the following folder structure:

/calculator
  ├── index.html
  ├── styles.css
  └── script.js
  • index.html: This file will contain the HTML structure for your calculator, including the display area and buttons.
  • styles.css: This file will handle all the styling, making sure the calculator looks good and is responsive across devices.
  • script.js: This is where you’ll write the logic to handle user input, perform calculations, and update the display.

By organizing the project in this way, we ensure that the calculator using HTML, CSS, and JavaScript is easy to maintain and expand upon in the future.

2. Linking HTML, CSS, and JavaScript Files

Now that we have our folder structure in place, we need to link the HTML, CSS, and JavaScript files together to make the calculator work. Here’s how to do it:

1. Linking the CSS File in HTML: In your index.html file, link the styles.css file in the <head> section:

<link rel="stylesheet" href="styles.css">

2. Linking the JavaScript File: In the <body> section of index.html, add a script tag to link the script.js file:

<script src="script.js"></script>

This ensures that your JavaScript calculator will be loaded and executed after the HTML structure is ready.

Final Structure in index.html

Here’s how the basic HTML file should look with both the CSS and JavaScript files linked:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <!-- Calculator layout goes here -->
  <script src="script.js"></script>
</body>
</html>

With the HTML, CSS, and JavaScript files properly linked, you're now ready to start building the actual calculator using JavaScript. This organization ensures that the components interact seamlessly to deliver a smooth user experience.

Learn how to build a calculator using Python 

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?


Step2. Building the HTML Structure

The first step in building our calculator is to create the HTML structure. HTML provides the skeleton of the calculator, which includes the display for showing results and buttons for user interaction. We'll define the layout and structure of the calculator elements.

Here’s the boilerplate code for the HTML document:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Calculator - By Upgrad</title>
    <!-- Link to external CSS file for styling -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <!-- Main container for the calculator -->
    <div class="calculator-container">
      <!-- Display area where numbers and results are shown -->
      <input type="text" id="display" class="display" disabled />

      <!-- Buttons for the calculator -->
      <div class="buttons">
        <button class="btn clear" id="clear">C</button>
        <button class="btn backspace" id="backspace">←</button>
        <button class="btn operator" id="divide">/</button>
        <button class="btn operator" id="multiply">*</button>

        <button class="btn" id="7">7</button>
        <button class="btn" id="8">8</button>
        <button class="btn" id="9">9</button>
        <button class="btn operator" id="subtract">-</button>

        <button class="btn" id="4">4</button>
        <button class="btn" id="5">5</button>
        <button class="btn" id="6">6</button>
        <button class="btn operator" id="add">+</button>

        <button class="btn" id="1">1</button>
        <button class="btn" id="2">2</button>
        <button class="btn" id="3">3</button>
        <button class="btn equals" id="equals">=</button>

        <button class="btn" id="0">0</button>
        <button class="btn" id="decimal">.</button>
      </div>
    </div>
    
    <!-- Link to external JavaScript file for functionality -->
    <script src="script.js"></script>
  </body>
</html>

Calculator html

Explanation of HTML:

  • The HTML structure defines the container (div.calculator-container) that holds the display and buttons of the calculator.
  • The input field with id="display" is used for showing the numbers or results.
  • The div.buttons contains all the buttons of the calculator (numbers, operators, and function buttons).
  • We link the CSS file for styling and the JavaScript file for functionality at the end of the body.

Step3. CSS (style.css)

Now, let's add CSS to style our calculator. We'll define the general layout, button styles, and the look of the display. The goal is to make the calculator visually appealing and easy to use.

/* Resetting default margin and padding for a clean slate */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Body and overall page styling */
body {
   /* Font for the whole body */
  background-color: #f4f4f4; /* Light gray background for the page */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full viewport height */
  margin: 0;
}

/* Container styling for the calculator */
.calculator-container {
  width: 320px; /* Fixed width for the calculator */
  background-color: #fff; /* White background for the calculator */
  border-radius: 10px; /* Rounded corners for a modern look */
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); /* Soft shadow effect */
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px; /* Space between elements */
}

/* Display area styling */
.display {
  width: 100%; /* Full width of the container */
  height: 50px; /* Set height of the display area */
  font-size: 24px; /* Font size for numbers */
  text-align: right; /* Right-align the text in the display */
  padding: 10px;
  background-color: #f9f9f9; /* Light background for the display */
  border: 1px solid #ccc; /* Border around the display */
  border-radius: 5px; /* Rounded corners for the display */
  margin-bottom: 20px; /* Space below the display */
  color: #333; /* Dark text color */
}

/* Button layout in a grid (4 columns for calculator layout) */
.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 4 equal-width columns */
  grid-gap: 10px; /* Gap between buttons */
  width: 100%;
}

/* General button styling */
.btn {
  background-color: #f0f0f0; /* Light gray background */
  border: 1px solid #ccc; /* Border around each button */
  border-radius: 5px; /* Rounded corners for buttons */
  font-size: 18px; /* Font size for button text */
  padding: 20px; /* Padding inside the buttons */
  text-align: center; /* Center-align the text inside buttons */
  cursor: pointer; /* Pointer cursor on hover */
  transition: background-color 0.3s ease; /* Smooth transition for hover effect */
}

/* Hover effect for buttons */
.btn:hover {
  background-color: #ddd; /* Darker gray on hover */
}

/* Active state for buttons (when clicked) */
.btn:active {
  background-color: #bbb; /* Even darker on click */
}

/* Styling for operator buttons (addition, subtraction, etc.) */
.btn.operator {
  background-color: #f9a825; /* Yellow background for operators */
  color: white; /* White text */
}

.btn.operator:hover {
  background-color: #f57f17; /* Darker yellow on hover */
}

.btn.operator:active {
  background-color: #ff6f00; /* Even darker on click */
}

/* Styling for the 'C' (Clear) and 'Backspace' buttons */
.btn.clear {
  background-color: #d32f2f; /* Red background for clear */
  color: white; /* White text */
}

.btn.clear:hover {
  background-color: #c62828; /* Darker red on hover */
}

.btn.clear:active {
  background-color: #b71c1c; /* Even darker red on click */
}

/* Styling for the 'Equals' button */
.btn.equals {
  background-color: #388e3c; /* Green background for equals */
  color: white; /* White text */
}

.btn.equals:hover {
  background-color: #2c6b2f; /* Darker green on hover */
}

.btn.equals:active {
  background-color: #1b5e20; /* Even darker green on click */
}

Calculator CSS

Explanation of CSS:

  • Global Reset: The * selector ensures that all elements have no margin or padding by default, providing a clean slate for styling.
  • Body Styling: We use flex to center the calculator container on the screen both vertically and horizontally. The background color is set to a light gray, and the height takes up the full viewport (100vh).
  • Calculator Container: We set a fixed width for the calculator, applied a white background, rounded corners, and added a subtle shadow for a modern look.
  • Buttons: Buttons are displayed in a grid layout with 4 columns. Hover and active states are defined to provide interactivity.
  • Operator and Special Buttons: Operators (+-*/), clear (C), and equals (=) buttons have distinct colors to make them visually stand out from the number buttons

Step4.  JavaScript (script.js)

Now, we will add JavaScript to bring the calculator to life. The JavaScript will handle user interactions like clicking buttons, performing calculations, and updating the display based on user input.

// Get the display element and all button elements
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');

// Initialize a variable to store the current calculation input
let currentInput = '';

// Add event listeners for each button
buttons.forEach(button => {
  button.addEventListener('click', (e) => {
    const value = e.target.textContent; // Get the value of the clicked button

    if (value === 'C') {
      // If 'C' is clicked, clear the display and reset the input
      currentInput = '';
      display.value = '';
    } else if (value === '←') {
      // If '←' is clicked, remove the last character from input
      currentInput = currentInput.slice(0, -1);
      display.value = currentInput;
    } else if (value === '=') {
      // If '=' is clicked, evaluate the expression and show the result
      try {
        currentInput = eval(currentInput).toString(); // Use eval() to evaluate the math expression
        display.value = currentInput;
      } catch (error) {
        // If the expression is invalid, display 'Error'
        display.value = 'Error';
        currentInput = '';
      }
    } else {
      // For other buttons (numbers and operators), append the value to the current input
      currentInput += value;
      display.value = currentInput; // Update the display with the current input
    }
  });
});

Calculator js

Explanation of JavaScript:

  • Getting Elements: The display element is selected to update the screen, and buttons are selected to add event listeners.
  • Event Listeners: Each button triggers an event when clicked. The value of the button is used to update the currentInput and the display.
  • Handling Special Buttons:
    • The Clear button (C) resets the input.
    • The Backspace button () removes the last character from the input.
    • The Equals button (=) evaluates the mathematical expression entered by the user using JavaScript's built-in eval() function. If the expression is invalid, it shows "Error".
  • Default Behavior: For number and operator buttons, the clicked value is added to the current input, and the display is updated.

If you're interested in learning how to build a calculator in C, we invite you to explore our detailed tutorial. This step-by-step guide will walk you through the process of creating a functional calculator program using C.

Conclusion:

You now have a complete and functional calculator using HTML, CSS, and JavaScript. The comments in the code explain each part of the project, and the explanations at the end of each section provide context for what each part of the code does. This should help you or any reader understand how the calculator works and how each technology contributes to the final result.

If you enjoyed building this calculator and are eager to dive deeper into web developmentJavaScript, or full-stack programming, UpGrad offers industry-leading courses designed to help you master these skills and advance your career.

  • Master Web Development with hands-on projects and expert mentorship.
  • Learn JavaScript in-depth and become proficient in building interactive web applications.
  • Expand Your Knowledge with courses on Frontend and Backend technologies.

Join UpGrad today and start building your future as a web developer. Don't wait—your journey to becoming an expert developer begins now! Feel free to test the code by copying and pasting it into an online code editor to see the result in action!

Enhance your expertise with our Software Development Free Courses. Explore the programs below to find your perfect fit.

Elevate your expertise with our range of Popular Software Engineering Courses. Browse the programs below to discover your ideal fit.

Advance your in-demand software development skills with our top programs. Discover the right course for you below.

Explore popular articles related to software to enhance your knowledge. Browse the programs below to find your ideal match.

Frequently Asked Questions (FAQs)

1. How do I build a simple calculator using HTML, CSS, and JavaScript?

To build a calculator using HTML, CSS, and JavaScript:

  • HTML provides the layout and structure (buttons, display area).
  • CSS styles the calculator (buttons, grid layout, display area).
  • JavaScript adds functionality, handling button clicks, calculations, and updating the display.

Start by creating an HTML layout, style it with CSS, and add interactivity using JavaScript to make the calculator work.

2. How can I style a calculator using CSS to make it look modern?

To style your calculator using CSS:

  • Use CSS Grid to arrange the calculator buttons in a grid format.
  • Set button hover effects and active states for better user interaction.
  • Ensure responsive design with media queries so the calculator looks good on both desktop and mobile devices.

Example: You can make buttons have a smooth transition on hover using transition: background-color 0.3s ease;.

3. What are some CSS techniques for creating a responsive calculator layout?

To create a responsive calculator layout:

  • Use CSS Flexbox or Grid for flexible layouts that adjust to different screen sizes.
  • Implement media queries to adjust button sizes and layout based on the viewport size.
  • Use relative units like %vw, and vh for width and height, making sure your calculator resizes gracefully across devices.
  • Example : 

@media (max-width: 600px) {

  .calculator-container {

    width: 100%;

  }

}

4. How do I link CSS and JavaScript files to my HTML document for a calculator?

To link CSS and JavaScript files in an HTML document:

1. In your HTML file, link the CSS file inside the <head> section:
html

<link rel="stylesheet" href="style.css" />

2. Link the JavaScript file before the closing </body> tag:

<script src="script.js"></script>

5. How does JavaScript handle the calculator logic for user input and calculations?

In JavaScript, you can handle the logic for a calculator by:

  • Listening to button clicks with event listeners.
  • Storing user input in a variable (e.g., currentInput).
  • Using JavaScript's eval() function to evaluate mathematical expressions entered by the user.
  • Updating the display based on user actions.

Example:

document.querySelector('.btn').addEventListener('click', function() {

  // Process button click

  // Update the display

});

6. What are some common mistakes when building a calculator with JavaScript?

Common mistakes when building a calculator using JavaScript include:

  • Using eval() without validation, which can expose your code to security risks. Always validate inputs before evaluating.
  • Not resetting the display correctly after each operation.
  • Not handling edge cases, such as division by zero or invalid input (e.g., entering multiple decimal points).

7. How can I implement keyboard support for my JavaScript calculator?

To implement keyboard support in your JavaScript calculator:

  • Use the keydown or keyup event listeners to capture key presses.
  • Map the key codes for numbers, operators, and the Enter key to trigger the corresponding calculator functions.

Example:

document.addEventListener('keydown', function(event) {

  if (event.key === '1') {

    // Add '1' to the input

  }

  if (event.key === 'Enter') {

    // Evaluate the expression

  }

});

8. How do I create a calculator with multiple decimal points in JavaScript?

To prevent multiple decimal points in a number:

  • Check if the current input already contains a decimal before adding another one.
  • If it doesn’t, add the decimal point; if it does, ignore the input.

Example:

if (!currentInput.includes('.')) {

  currentInput += '.';

}

9. How can I debug JavaScript errors in my calculator?

To debug JavaScript errors in your calculator:

  • Use the browser's developer tools (DevTools) to inspect the console for errors.
  • Insert console.log() statements at different points in your JavaScript to track variable values and flow.
  • Use try...catch blocks around functions like eval() to catch any errors during evaluation.

Example:

try {

  let result = eval(currentInput);

} catch (e) {

  console.error('Error:', e);

  display.value = 'Error';

}

10. How do I clear the display in a JavaScript calculator?

To clear the display in a JavaScript calculator, you need to:

  • Set the input variable (currentInput) to an empty string when the "Clear" button is clicked.
  • Update the display to reflect the cleared input.

Example:

document.getElementById('clear').addEventListener('click', function() {

  currentInput = '';

  display.value = '';

});

11. What are some performance optimization tips for a JavaScript calculator?

To optimize the performance of a JavaScript calculator:

  • Minimize DOM manipulation (e.g., only update the display when necessary).
  • Avoid using global variables. Use functions to scope variables locally.
  • If you use complex math functions, ensure efficient algorithms are used to handle large numbers or calculations.

RELATED PROGRAMS