Skip to main content

HTML Calculator Tutorial for Beginners — Build a Calculator with HTML, CSS & JavaScript

Calculator tutorial banner

HTML Calculator Tutorial for Beginners — Build a Calculator with HTML, CSS & JavaScript

Learn to create a clean, responsive calculator step-by-step. Includes source code you can copy, a live demo, FAQ, and schema markup — optimized for Blogger.

⏱️ Estimated read: 6 min · 📁 Category: HTML / JavaScript
Ad space — place your AdSense / banner here (300×250 / responsive)

Introduction

In this tutorial you'll build a simple but robust calculator using plain HTML, CSS and JavaScript. The app supports clicking buttons, keyboard input, decimal points, clear and backspace, and safe evaluation. Use the copy buttons to copy code blocks, or the run buttons to preview the app instantly.

Step 1 — HTML Structure

Create the basic markup for the calculator. This includes a display, buttons, and a small history area.


<div class="calc-container" role="application" aria-label="Calculator">
  <input id="display" class="calc-display" aria-label="Calculator display" disabled />
  <div class="calc-buttons">
    <button data-val="7">7</button>
    <button data-val="8">8</button>
    <button data-val="9">9</button>
    <button data-op="/" aria-label="divide">/</button>
    <button data-val="4">4</button>
    <button data-val="5">5</button>
    <button data-val="6">6</button>
    <button data-op="*" aria-label="multiply">*</button>
    <button data-val="1">1</button>
    <button data-val="2">2</button>
    <button data-val="3">3</button>
    <button data-op="-" aria-label="subtract">-</button>
    <button data-val="0">0</button>
    <button data-val=".">.</button>
    <button id="equal" aria-label="equals">=</button>
    <button data-op="+" aria-label="add">+</button>
    <button id="back" title="Backspace">⌫</button>
    <button id="clear" style="grid-column: span 3; background:#ef4444; color:#fff;">CLEAR</button>
  </div>
  <div id="history" aria-live="polite" style="margin-top:12px;font-size:13px;color:#555;"></div>
</div>
      

Step 2 — CSS Styling

Add modern, responsive styles that look good on desktop and mobile.


.calc-container {
  width: 100%;
  max-width: 320px;
  margin: 18px auto;
  background: #fff;
  padding: 18px;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(2,6,23,0.06);
  font-family: Inter, Roboto, Arial, sans-serif;
}
.calc-display {
  width: 100%;
  height: 56px;
  font-size: 22px;
  text-align: right;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #e6edf3;
  margin-bottom: 12px;
  background:#f8fafc;
}
.calc-buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap:10px;
}
.calc-buttons button {
  height:46px;
  font-size:18px;
  border: none;
  border-radius:8px;
  background:#0ea5e9;
  color:#fff;
  cursor:pointer;
}
.calc-buttons button:active { transform: scale(0.98); }
#back { background:#f59e0b; }
#equal { background:#10b981; }
@media (max-width:420px){
  .calc-container { padding:14px; }
  .calc-display { height:48px; font-size:20px; }
}
      

Step 3 — JavaScript Logic

This script handles button clicks, keyboard support, safe evaluation, and a small history.


(function(){
  const display = document.getElementById('display');
  const buttons = document.querySelectorAll('.calc-buttons button[data-val], .calc-buttons button[data-op]');
  const equal = document.getElementById('equal');
  const clearBtn = document.getElementById('clear');
  const backBtn = document.getElementById('back');
  const history = document.getElementById('history');

  function safeEval(expr){
    if(!/^[0-9+\-*/.()\s]+$/.test(expr)) throw new Error('Invalid characters');
    return eval(expr);
  }

  buttons.forEach(btn => {
    btn.addEventListener('click', () => {
      const v = btn.getAttribute('data-val') || btn.getAttribute('data-op');
      display.value += v;
    });
  });

  equal.addEventListener('click', () => {
    try{
      const expr = display.value.trim();
      if(!expr) return;
      const result = safeEval(expr);
      history.innerText = expr + ' = ' + result;
      display.value = String(result);
    } catch(err){
      alert('Invalid expression');
    }
  });

  clearBtn.addEventListener('click', () => display.value = '');
  backBtn.addEventListener('click', () => display.value = display.value.slice(0,-1));

  document.addEventListener('keydown', e => {
    if(e.key === 'Enter') { equal.click(); e.preventDefault(); }
    else if(e.key === 'Backspace') backBtn.click();
    else if(e.key === 'Escape') clearBtn.click();
    else if(/^[0-9+\-*/().]$/.test(e.key)) display.value += e.key;
  });
})();
      

Live Demo

FAQ

Can I extend this to a scientific calculator?

Yes — add buttons for sin, cos, tan, log, sqrt and implement them using JavaScript Math functions.

Is using eval() safe here?

We use a small safeEval() that first validates the expression to contain only numbers, parentheses, spaces, and operators before calling eval(). For large apps, consider implementing a proper expression parser.

How to add history or memory?

You can push results to an array and render them beneath the calculator or persist them with localStorage.

Schema & SEO

JSON-LD HowTo schema is included at the top. Set your Blogger post's Title and Search Description for best SEO results.

Related Tutorials

Ad space — 728×90 / responsive banner
© Your Blog Name • Built with HTML & JavaScript

Comments

Popular posts from this blog

HTML Forms Tutorial HTML Forms Tutorial HTML Forms allow users to enter and submit data. They are used everywhere—login forms, signup forms, search boxes, feedback forms, etc. In this complete tutorial, you will learn all form elements with examples and demos. 1. What is an HTML Form? A form collects user input using different form elements like text fields, checkboxes, radio buttons, buttons, and more. <form> Form elements go here... </form> 2. Basic Form Structure <form action="#" method="post"> <input type="text" placeholder="Enter name"> <button>Submit</button> </form> Submit Attributes: action → URL where form data is sent method="POST" → Secure data sending method="GET" → Data shows in URL 3. Text Input Field <i...
📸 HTML Image Gallery Tutorial for Beginners Image galleries make your website more beautiful and professional. In this tutorial, you will learn how to create different types of image galleries using HTML and CSS. 📌 1. Simple HTML Image Gallery This is the most basic gallery layout. <div> <img src="image1.jpg" width="200"> <img src="image2.jpg" width="200"> <img src="image3.jpg" width="200"> </div> ✔ Explanation All images are inside a <div> Each image has the same width They appear in a row 📌 2. Responsive Image Gallery (CSS Grid) This gallery automatically adjusts on mobile and PC. <style> .gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; } .gallery img { width: 100%; border-radius: 10px; } </style> <div class="galle...
📝 HTML Notes App Tutorial for Beginners (Full Project) In this tutorial, you will learn how to build a fully functional Notes App using HTML, CSS, and JavaScript. This app works on all devices and saves notes even after refreshing the page! ✨ Features of This Notes App Add new notes Edit notes Delete notes Dark Mode Search notes Auto-save using LocalStorage No backend needed 📌 Step 1 — HTML Structure Copy Code Run Demo <div class="container"> <h1>Notes App</h1> <button id="toggleDark">🌙 Dark Mode</button> <input type="text" id="searchBox" placeholder="Search notes..."> <textarea id="noteInput" placeholder="Write your note here..."></textarea> <button id="addNote">Add Note</button> <div id="notesList"></div> ...
HTML Tags Tutorial – A Complete Beginner-Friendly Guide HTML tags are the basic building blocks of every webpage. Whether you want to create a simple webpage or a full website, understanding HTML tags is the first and most important step. In this post, we’ll explore what HTML tags are, how they work, why they matter, and the most commonly used tags with examples. Table of Contents What Are HTML Tags? How HTML Tags Work Types of HTML Tags Most Common HTML Tags Self-Closing Tags Nesting Tags Practical Examples Best Practices What Are HTML Tags? HTML tags are keywords enclosed in angle brackets < > that tell the browser how to display content. Tags create elements such as headings, paragraphs, images, links, lists, buttons, forms, and much more. Example of a simple tag: <p>This is a paragraph.</p> How HTML Tags Work Most HTML tags come in pairs: <opening-tag>...
HTML Images Tutorial HTML Images Tutorial The <img> tag is used to display images on a webpage. In this tutorial, you'll learn how to add images, resize them, add borders, captions, and more. 1. Basic Image Tag The simplest way to add an image is by using the src and alt attributes. <img src="image.jpg" alt="My Image"> Attributes: src → Image URL alt → Text shown if image fails to load 2. Image Size (width & height) You can resize an image using width or height . <img src="photo.jpg" width="300" height="200"> 3. Responsive Images Responsive images automatically adjust to device size. <img src="photo.jpg" style="width:100%;max-width:400px;"> 4. Add Border to Images <img src="file.jpg" style="border:3px solid #333;...