🧮

Building a Simple Calculator with JavaScript

Aug 6, 2024

Simple Calculator Project with Vanilla JavaScript

Overview

  • Building a simple calculator using plain vanilla JavaScript and modern ES6 practices.
  • Features include basic arithmetic operations, decimal support, chaining operations, and clear/delete functionality.

Calculator Functionality

  1. Basic Operations:
    • Addition (+), Multiplication (×), Subtraction (−), Division (÷)
    • Supports decimal numbers.
  2. Special Functions:
    • Delete key: removes one character from the display.
    • All Clear (AC): resets the display.
  3. Chaining Operations:
    • Allows operations to be chained together.

Setting Up the Project

  1. Create necessary files:
    • index.html for HTML structure.
    • styles.css for styling.
    • script.js for JavaScript functionality.
  2. HTML Setup:
    • Use a boilerplate for index.html:
      • Set title to "Calculator".
      • Link styles.css and script.js using appropriate <link> and <script> tags with defer attribute.
  3. Calculator Layout:
    • Use a grid layout for buttons and display.
    • Create an output display and number buttons (0-9, decimal, operations).

CSS Styling

  1. Base Styles:
    • Select all elements and set box-sizing to border-box, set a default font family, and weight.
  2. Background & Layout:
    • Apply a linear gradient background.
    • Center grid items using display: grid, justify-content, and align-items properties.
  3. Button Styles:
    • Set cursor to pointer and customize button sizes and colors.
    • Add hover effects to buttons.
  4. Output Styles:
    • Set display and alignment for the output area.
    • Use flexbox for aligning text elements.

JavaScript Functionality

  1. Selecting Elements:
    • Use querySelector and querySelectorAll to select buttons and display elements.
  2. Calculator Class:
    • Define a Calculator class to manage operations, input, and display.
    • Include methods for clear, delete, append number, choose operation, compute result, and update display.
  3. Event Listeners:
    • Add event listeners to buttons to handle user interactions.
    • Update display values appropriately based on user actions.
  4. Computation Logic:
    • Implement logic for operation selection and calculation using a switch statement.
    • Handle cases for invalid input and display formatted results.

Final Touches

  • Ensure proper function execution on button clicks, including chaining operations and clearing values correctly.
  • Implement comma separation for large numbers in display.
  • Add functionality to handle decimal inputs properly and ensure correct formatting.

Conclusion

  • The calculator is functional and visually styled.
  • Encouragement to check out other projects and subscribe for more tutorials.