How to Make a Simple JavaScript Calculator

Introduction-Hey there, future coder! 🤖 Today, we’re going to build a simple calculator using HTML, CSS, and JavaScript.

Step 1: Create the HTML (The Bones)
HTML is like the skeleton of a web page. It tells the computer what parts we need.
Open a text editor (like Notepad or VS Code).
Save a file called calculator.html
Copy and paste this code:

<!DOCTYPE html>
<html>
<head>
  <title>Simple Calculator</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="calculator">
    <input type="text" id="display" disabled>
    <div class="buttons">
      <button onclick="clearDisplay()">C</button>
      <button onclick="appendValue('1')">1</button>
      <button onclick="appendValue('2')">2</button>
      <button onclick="appendValue('+')">+</button>
      <button onclick="appendValue('3')">3</button>
      <button onclick="appendValue('4')">4</button>
      <button onclick="appendValue('-')">-</button>
      <button onclick="appendValue('5')">5</button>
      <button onclick="appendValue('6')">6</button>
      <button onclick="appendValue('*')">*</button>
      <button onclick="appendValue('7')">7</button>
      <button onclick="appendValue('8')">8</button>
      <button onclick="appendValue('/')">/</button>
      <button onclick="appendValue('9')">9</button>
      <button onclick="appendValue('0')">0</button>
      <button onclick="calculate()">=</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Step 2: Add the CSS (The Style)
CSS makes your calculator look nice. Like giving it color and style!
Save a file called style.css
Copy and paste this code:

body {
  font-family: Arial, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.calculator {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

#display {
  width: 100%;
  height: 40px;
  margin-bottom: 10px;
  font-size: 20px;
  text-align: right;
}

.buttons button {
  width: 60px;
  height: 40px;
  margin: 5px;
  font-size: 18px;
}

Step 3: Write the JavaScript (The Brain)
JavaScript makes the calculator work. It does all the thinking!
Save a file called script.js
Copy and paste this code:

function appendValue(value) {
  document.getElementById('display').value += value;
}

function clearDisplay() {
  document.getElementById('display').value = '';
}

function calculate() {
  let result = eval(document.getElementById('display').value);
  document.getElementById('display').value = result;
}

Try Other Projects

Whether you’re curious about features, a free trial, or even press, we’re here to answer any questions.