Simple Calculator Using HTML, CSS & JavaScript

Published by Pawan Sargar on

Calculator using HTML, CSS & JavaScript

Today, in this post we’ll learn how to create a simple yet beautiful calculator using our plain old HTML, CSS & JavaScript.

If you are just beginning your journey in Web Development, especially in JavaScript, creating a Calculator will give you a brief idea about how JavaScript DOM manipulation works.

So, let’s get into our favorite code editor.

This is what we’ll create.

Starting Files –

Go ahead and create first 3 starting files and all the boiler plate code.

  • index.html
  • styles.css
  • index.js

HTML Code –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>calculator</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <div class="calculator">
        <input type="text" id="input" />
        <table>
          <tr>
            <td><button>1</button></td>
            <td><button>2</button></td>
            <td><button>2</button></td>
            <td><button>C</button></td>
          </tr>
          <tr>
            <td><button>7</button></td>
            <td><button>8</button></td>
            <td><button>9</button></td>
            <td><button>X</button></td>
          </tr>
          <tr>
            <td><button>4</button></td>
            <td><button>5</button></td>
            <td><button>6</button></td>
            <td><button>-</button></td>
          </tr>
          <tr>
            <td><button>1</button></td>
            <td><button>2</button></td>
            <td><button>3</button></td>
            <td><button>+</button></td>
          </tr>
          <tr>
            <td><button>0</button></td>
            <td><button>.</button></td>
            <td><button>/</button></td>
            <td><button>=</button></td>
          </tr>
        </table>
      </div>
    </div>
    <script src="index.js"></script>
  </body>
</html>

So, nothing fancy here, we have a container wrapping the table element. Inside the table we have 5 rows and inside those rows, we have table data, which are nothing but Calculator Buttons.

If you don’t know HTML Table element then checkout this W3Schools Documentation.

Also, we are linking to external stylesheet & script.

CSS Code –

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400;600&display=swap');
body {
    font-family: 'Montserrat', sans-serif;
    height: 100vh;
    background: #ff9966;  /* fallback for old browsers */
    background: -webkit-linear-gradient(to right, #ff5e62, #ff9966);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to right, #ff5e62, #ff9966); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */    
    text-align: center;
}
.calculator {
    display: inline-block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
input, button {
    border: none;
    outline: none;
    height: 50px;
}
input {
    width: 321px;
    font-size: 30px;
    margin-bottom: -1px;
    background-color:#333A4D;
    color:#EEEEEE;
}
button {
    margin: -1px;
    font-family: 'Montserrat', sans-serif;
    font-weight: 600;
    font-size: 2rem;
    background-color: #EEEEEE;
    width: 80px;
    color: #333A4D;
}
button:active {
    background-color: #333A4D;
    color: #EEEEEE;
}

Here, we have imported a Google Font called Montserrat and have a background gradient. I’ve used UI Gradients to get this beautiful background gradient.

Else, we are not using any fancy CSS, just the basics you might already be familiar with.

JavaScript Code –

let input = document.getElementById("input");
let buttons = document.querySelectorAll("button");
let inputValue = "";

for (item of buttons) {
  item.addEventListener("click", (e) => {
    buttonText = e.target.innerText;
    console.log("button text is ", buttonText);

    if (buttonText == "X") {
      buttonText = "*";
      inputValue += buttonText;
      input.value = inputValue;

    } else if (buttonText == "C") {
      inputValue = "";
      input.value = inputValue;

    } else if (buttonText == "=") {
      input.value = eval(inputValue);
      
    } else {
      inputValue += buttonText;
      input.value = inputValue;
    }
  });
}

So, I’ll explain the JavaScript part with steps so that you’d be able to understand it properly without getting confused.

  • First, we are getting the hold of the Input & button elements from HTML using basic DOM manipulation methods.
  • Declaring the inputValue as an empty variable, because we’ll update the text inside button on every click. Also, it will be evaluated and give us the results when we click on the = equal button.
  • Now, we are using a for a loop. As we already have the hold of all buttons, which is also an array, so it makes sense to loop through all buttons and add event listeners on each button. So, here item of buttons means, for every single button from the buttons array add an event listener click.
  • It is also required to hold the text inside the button, we can do that by simply getting its value. So the e.target.innerText will give us the text inside the buttons.
  • So, now, it’s just some if-else statements, checking the button text and the only changing we need to do is of multiply as "X" won’t get evaluated, instead, we need asterisks "*" which acts as multiply.
  • The JavaScript eval() method, executes the string we pass in it as an argument. That’s why we used all input types as strings. Also, it only executes JavaScript expressions. So, as 1 + 1 is a valid JS expression.

I hope this post was helpful, if it was make sure to share it with your friends who are just starting out their journey as a web developers. Also, make sure to follow our Coding Master Newsletter for more interesting web development posts.

Pawan Sargar
Follow him
```html ```

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *