🧮

Web Calculator Guide

Jun 12, 2025

Overview

This lecture covers how to build a functional calculator web app using HTML, CSS, and JavaScript, including layout creation, style customization, and interactive behavior.

HTML Structure

  • Create a <div> with ID calculator as the main container.
  • Add an <input> with ID display and the readonly attribute to show results and prevent direct user input.
  • Nest another <div> with ID keys inside the calculator for all button elements.
  • Create buttons for digits (0-9), operators (+, -, *, /), decimal point, equals (=), and clear (C).
  • Assign appropriate onclick attributes: operator/digit/decimal buttons call appendToDisplay(), equals calls calculate(), clear calls clearDisplay().
  • Add a class operator-btn to operator and clear buttons for special styling.*

CSS Styling

  • Set all buttons to 100x100px, circular with border-radius: 50px, no border, dark background, white bold text, and pointer cursor on hover.
  • Arrange buttons in a 4-column grid using CSS Grid on #keys with a 10px gap and 25px padding.
  • Style the calculator container with a dark background, rounded corners, max-width 500px, hidden overflow, and Arial font.
  • Style the display to span 100% width, large font, padded, left-aligned, no border, and slightly lighter background.
  • Center calculator in the viewport using Flexbox, setting body height to 100vh and background to a very light color.
  • Add hover and active effects to buttons by increasing background lightness.
  • Style operator and clear buttons with orange background and lighter shades on hover/active.

JavaScript Functionality

  • Select display element with document.getElementById('display').
  • Define three functions: appendToDisplay(input), clearDisplay(), and calculate().
  • appendToDisplay(input): Concatenates the input character to the display's current value.
  • clearDisplay(): Sets display value to an empty string to clear it.
  • calculate(): Uses eval() to evaluate the expression in the display; uses try-catch for error handling, displays "Error" if invalid.

Key Terms & Definitions

  • readonly attribute — Prevents user from directly editing the input field.
  • CSS Grid — Layout system to arrange elements in a grid structure.
  • Flexbox — CSS layout mode for easy centering of containers.
  • eval() — JavaScript function that evaluates a string as code.
  • try-catch — JavaScript error handling structure for exceptions.

Action Items / Next Steps

  • Review the full code for HTML, CSS, and JavaScript implementation.
  • Test calculator functions in your browser.
  • Experiment with adding new features or changing styles.