Projects

Building a Simple Calculator with HTML, CSS, and JavaScript

Introduction to the JavaScript Calculator

Welcome to the beginner-friendly tutorial on building a JavaScript Calculator! In this project, we'll create a fully functional calculator that can perform basic and advanced operations. This project is an excellent way to learn how to work with event listeners, complex logic, and DOM manipulation.

Setting Up Your Workspace

Creating Your Project Folder and Files

Before we begin coding, let's set up a workspace for our project. This folder will be your digital canvas, where you'll keep all the project files organized.

Step 1: Create Your Project Folder

Create a new folder on your computer to store all your project files. You can name it "javascript-calculator".

On Windows:
  1. Right-click on your desktop.
  2. Choose "New" > "Folder".
  3. Name it "javascript-calculator".
On Mac:
  1. Right-click on your desktop.
  2. Choose "New Folder".
  3. Name it "javascript-calculator".

Step 2: Get Your Text Editor Ready

You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.

  1. Download Visual Studio Code from code.visualstudio.com.
  2. Install it on your computer.
  3. Open VS Code and drag your "javascript-calculator" folder into the window.

Step 3: Create Your Project Files

We need three essential files for our project:

To create these files:

  1. Open VS Code.
  2. index.html - Click "New File" and save it as "index.html".
  3. styles.css - Click "New File" again and save it as "styles.css".
  4. script.js - Click "New File" once more and save it as "script.js".

🎯 Success Check: You should now have:

👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.

Setting Up the HTML Structure

Creating the Calculator HTML

Let's start by building the HTML structure for our calculator. HTML is like the foundation of our app.

  1. 1. Open "index.html": Open your "index.html" file in your code editor.
  2. 2. Add the Calculator HTML: Copy and paste the following code into your "index.html" file:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>JavaScript Calculator</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <div class="container">
        <h1>JavaScript Calculator</h1>
        <div id="calculator">
          <input type="text" id="display" disabled>
          <div class="buttons">
            <button class="btn" id="clear">C</button>
            <button class="btn" id="delete">DEL</button>
            <button class="btn" id="divide">/</button>
            <button class="btn" id="multiply">*</button>
            <button class="btn" id="seven">7</button>
            <button class="btn" id="eight">8</button>
            <button class="btn" id="nine">9</button>
            <button class="btn" id="subtract">-</button>
            <button class="btn" id="four">4</button>
            <button class="btn" id="five">5</button>
            <button class="btn" id="six">6</button>
            <button class="btn" id="add">+</button>
            <button class="btn" id="one">1</button>
            <button class="btn" id="two">2</button>
            <button class="btn" id="three">3</button>
            <button class="btn" id="equals">=</button>
            <button class="btn" id="zero">0</button>
            <button class="btn" id="decimal">.</button>
          </div>
        </div>
      </div>
      <script src="script.js"></script>
    </body>
    </html>

Let's break down the HTML structure:

Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice! 🎨

Styling the Calculator

Adding CSS Styles

CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our calculator.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Calculator Styles: Copy and paste the following CSS code into your "styles.css" file:
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      background-color: #f4f4f4;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .container {
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      width: 300px;
      text-align: center;
    }
    
    h1 {
      margin: 0 0 20px;
      font-size: 1.5rem;
    }
    
    #calculator {
      text-align: left;
    }
    
    #display {
      width: 100%;
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 1.2rem;
      text-align: right;
    }
    
    .buttons {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;
    }
    
    .btn {
      width: 100%;
      padding: 15px;
      border: none;
      border-radius: 5px;
      font-size: 1rem;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }
    
    .btn:hover {
      background-color: #f0f0f0;
    }
    
    #clear, #delete, #equals {
      background-color: #007bff;
      color: #fff;
    }
    
    #clear:hover, #delete:hover, #equals:hover {
      background-color: #0056b3;
    }
    
    #divide, #multiply, #subtract, #add {
      background-color: #ff9800;
      color: #fff;
    }
    
    #divide:hover, #multiply:hover, #subtract:hover, #add:hover {
      background-color: #ff8c00;
    }
    
    #decimal, #zero, #one, #two, #three, #four, #five, #six, #seven, #eight, #nine {
      background-color: #4a90e6;
      color: #fff;
    }
    
    #decimal:hover, #zero:hover, #one:hover, #two:hover, #three:hover, #four:hover, #five:hover, #six:hover, #seven:hover, #eight:hover, #nine:hover {
      background-color: #3a7cbb;
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled calculator. 🎉

Adding JavaScript for User Interactions

Handling Button Clicks

Now, let's add JavaScript to make our calculator interactive! We'll handle button clicks and perform calculations.

Selecting HTML Elements

First, we need to select the HTML elements we want to work with. We'll select the display input and all the buttons.

  1. 1. Open "script.js": Open the "script.js" file in your code editor.
  2. 2. Selecting Elements: Copy and paste the following JavaScript code into your "script.js" file:
    // Selecting HTML elements
    const display = document.getElementById('display');
    const buttons = document.querySelectorAll('.btn');

Here, we're using the getElementById andquerySelectorAll methods to select the display input and all the buttons.

Handling Button Clicks

Next, we'll create a function to handle button clicks. This function will determine what to do based on the button clicked.

  1. 3. Handling Button Clicks: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to handle button clicks
    function handleButtonClick(event) {
      const button = event.target;
      const value = button.textContent;
    
      if (button.id === 'clear') {
        clearCalculator();
      } else if (button.id === 'delete') {
        deleteLastCharacter();
      } else if (button.id === 'equals') {
        calculateResult();
      } else {
        updateDisplay(value);
      }
    }

This function checks the ID of the button clicked and calls the appropriate function based on the button's ID.

Clearing the Calculator

Now, let's create a function to clear the calculator display.

  1. 4. Clearing the Calculator: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to clear the calculator
    function clearCalculator() {
      display.value = '';
    }

This function sets the display value to an empty string, effectively clearing the display.

Deleting the Last Character

Next, let's create a function to delete the last character from the display.

  1. 5. Deleting the Last Character: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to delete the last character
    function deleteLastCharacter() {
      display.value = display.value.slice(0, -1);
    }

This function uses the slice method to remove the last character from the display value.

Updating the Display

Now, let's create a function to update the display with the value of the button clicked.

  1. 6. Updating the Display: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to update the display
    function updateDisplay(value) {
      if (value === 'C' || value === 'DEL' || value === '=') {
        return;
      }
      display.value += value;
    }

This function checks if the value is 'C', 'DEL', or '=' and returns early if it is. Otherwise, it appends the value to the display.

Calculating the Result

Finally, let's create a function to calculate the result of the expression in the display.

  1. 7. Calculating the Result: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to calculate the result
    function calculateResult() {
      const expression = display.value;
      try {
        const result = eval(expression);
        display.value = result.toString();
      } catch (error) {
        display.value = 'Error';
      }
    }

This function uses the eval function to evaluate the expression in the display. If the evaluation is successful, it sets the display value to the result. If an error occurs, it sets the display value to 'Error'.

Adding Event Listeners to Buttons

Now, let's add event listeners to all the buttons so that they trigger the handleButtonClick function when clicked.

  1. 8. Adding Event Listeners to Buttons: Copy and paste the following JavaScript code into your "script.js" file:
    // Adding event listeners to buttons
    buttons.forEach(button => {
      button.addEventListener('click', handleButtonClick);
    });

This code iterates over all the buttons and adds a click event listener to each one, calling the handleButtonClick function when a button is clicked.

Putting It All Together

Now that we have the HTML, CSS, and JavaScript in place, let's put it all together and test our calculator.

  1. 1. Save Your Files: Save the "index.html", "styles.css", and "script.js" files.
  2. 2. Open "index.html" in a Web Browser: Open your "index.html" file in a web browser to see your calculator in action.

If everything is working correctly, you should be able to perform basic and advanced operations using the calculator.

Final Thoughts

Congratulations! You've completed the JavaScript Calculator project. You've learned how to create a fully functional calculator that can perform basic and advanced operations. This project introduced you to working with event listeners, complex logic, and DOM manipulation.

Feel free to customize and expand your calculator further. You can add more features, improve the design, or even create a mobile version. Happy coding and exploring the world of web development! 🚀