DEV Community

Pratik Pathak
Pratik Pathak

Posted on • Originally published at pratikpathak.com on

iOS Calculator Javascript Project for beginner

Calculator Javascript Project is a web-based iOS-style calculator application. The HTML structure includes a screen for displaying calculations and a set of buttons for digits 0-9, arithmetic operations (addition, subtraction, multiplication, division), a clear function, a backspace function, and an equals button for calculating results.

Code for iOS Calculator Javascript Project

The visual styling of the application is linked via a CSS file named “style.css”, and the functionality is provided by a JavaScript file named “script.js”. The user can perform basic arithmetic operations by clicking the buttons on the calculator.

Live Preview | Source Code

Html:

<!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>iOS Calculator</title>
    <link rel="stylesheet" href="./style.css" />
  </head>

  <body>
    <div class="calc">
      <section class="screen">0</section>
      <section class="class-buttons">
        <div class="calc-row">
          <button class="double calc-button">C</button>
          <button class="calc-button"></button>
          <button class="calc-button">÷</button>
        </div>
        <div class="calc-row">
          <button class="calc-button">7</button>
          <button class="calc-button">8</button>
          <button class="calc-button">9</button>
          <button class="calc-button">×</button>
        </div>
        <div class="calc-row">
          <button class="calc-button">4</button>
          <button class="calc-button">5</button>
          <button class="calc-button">6</button>
          <button class="calc-button">-</button>
        </div>
        <div class="calc-row">
          <button class="calc-button">1</button>
          <button class="calc-button">2</button>
          <button class="calc-button">3</button>
          <button class="calc-button">+</button>
        </div>
        <div class="calc-row">
          <button class="tripple calc-button">0</button>
          <button class="calc-button">=</button>
        </div>
      </section>
    </div>

    <script src="./script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.calc {
  width: 480px;
  background-color: black;
  color: white;
}

.screen {
  font-size: 40px;
  font-family: "Courier New", Courier, monospace;
  text-align: right;
  padding: 20px 5px;
}

.calc-button {
  background-color: #d8d9db;
  color: black;
  height: 100px;
  width: 24.5%;
  border: none;
  border-radius: 0;
  font-size: 40px;
  cursor: pointer;
}

.calc-button:hover {
  background-color: #efeff0;
}

.calc-button:active {
  background-color: #aeafb1;
}

.calc-button:last-child {
  background-color: rgba(253, 169, 11, 0.795);
}

.calc-button:last-child:hover {
  background-color: rgba(243, 180, 63, 0.87);
  color: white;
}

.calc-button:last-child:active {
  background-color: rgba(170, 111, 2, 0.918);
}

.double {
  width: 49.7%;
}

.tripple {
  width: 74.8%;
}

.calc-row {
  display: flex;
  align-content: stretch;
  justify-content: space-between;
  margin-bottom: 0.5%;
}
Enter fullscreen mode Exit fullscreen mode

Js:


let runningTotal = 0;
let buffer = "0";
let previousOperator;
const screen = document.querySelector(".screen");

function buttonClick(value) {
  if (isNaN(parseInt(value))) {
    handleSymbol(value);
  } else {
    handleNumber(value);
  }
  rerender();
}

function handleNumber(value) {
  if (buffer === "0") {
    buffer = value;
  } else {
    buffer += value;
  }
}

function handleMath(value) {
  if (buffer === "0") {
    // do nothing
    return;
  }

  const intBuffer = parseInt(buffer);
  if (runningTotal === 0) {
    runningTotal = intBuffer;
  } else {
    flushOperation(intBuffer);
  }

  previousOperator = value;

  buffer = "0";
}

function flushOperation(intBuffer) {
  if (previousOperator === "+") {
    runningTotal += intBuffer;
  } else if (previousOperator === "-") {
    runningTotal -= intBuffer;
  } else if (previousOperator === "×") {
    runningTotal *= intBuffer;
  } else {
    runningTotal /= intBuffer;
  }
}

function handleSymbol(value) {
  switch (value) {
    case "C":
      buffer = "0";
      runningTotal = 0;
      break;
    case "=":
      if (previousOperator === null) {
        // need two numbers to do math
        return;
      }
      flushOperation(parseInt(buffer));
      previousOperator = null;
      buffer = +runningTotal;
      runningTotal = 0;
      break;
    case "":
      if (buffer.length === 1) {
        buffer = "0";
      } else {
        buffer = buffer.substring(0, buffer.length - 1);
      }
      break;
    case "+":
    case "-":
    case "×":
    case "÷":
      handleMath(value);
      break;
  }
}

function rerender() {
  screen.innerText = buffer;
}

function init() {
  document
    .querySelector(".class-buttons")
    .addEventListener("click", function (event) {
      buttonClick(event.target.innerText);
    });
}

init(); //init update

Enter fullscreen mode Exit fullscreen mode

25+ More Javascript Projects for beginners, click here to learn more https://pratikpathak.com/top-javascript-projects-with-source-code-github/

Now let’s go through each file one by one 🏃‍♂️…

index.html

This index.html file is the main HTML document for a simple web-based iOS-style calculator application.

Here’s a breakdown of the file:

  • The <!doctype html> declaration helps with browser compatibility.
  • The <html lang="en"> tag declares the language of the document to be English.
  • The <head> section contains meta information about the document, including the character set, viewport, and a link to the CSS stylesheet (style.css) for styling the page.
  • The <title> tag sets the title of the web page, which appears in the browser’s title bar or tab.
  • The <body> tag contains the main content of the web page.
  • Inside the <body> tag, there’s a <div> with the class calc, which serves as the container for the calculator.
  • The calculator screen is represented by a <section> with the class screen. It initially displays 0.
  • The buttons of the calculator are contained within another <section> with the class class-buttons. Each row of buttons is wrapped in a <div> with the class calc-row.
  • Each button is represented by a <button> element with the class calc-button. Some buttons have additional classes like double and tripple to adjust their width.
  • The calculator supports basic arithmetic operations: addition (+), subtraction (-), multiplication (×), and division (÷). It also has a clear button (C), a backspace button (), and an equals button (=) for calculating the result.
  • The <script> tag at the end of the <body> section links to a JavaScript file (script.js), which provides the functionality for the calculator.

style.css

This style.css file provides the styling for a web-based iOS-style calculator application. Here’s a breakdown of the CSS rules:

  • * { box-sizing: border-box; }: This rule applies the box-sizing property to all elements (*). The border-box value includes padding and border in the element’s total width and height.
  • body { padding: 0; margin: 0; }: This rule removes the default margin and padding from the <body> element.
  • .calc { width: 480px; background-color: black; color: white; }: This rule styles the calculator container. It sets the width, background color, and text color.
  • .screen { font-size: 40px; font-family: "Courier New", Courier, monospace; text-align: right; padding: 20px 5px; }: This rule styles the calculator screen. It sets the font size, font family, text alignment, and padding.
  • .calc-button {...}: This set of rules styles the calculator buttons. It sets the background color, text color, height, width, border, border radius, font size, and cursor style. It also defines hover and active states for the buttons.
  • .calc-button:last-child {...}: This set of rules styles the last button in each row (the equals button). It sets a different background color and defines hover and active states.
  • .double { width: 49.7%; } and .tripple { width: 74.8%; }: These rules adjust the width of buttons with the double and tripple classes, making them span two or three normal button widths, respectively.
  • .calc-row { display: flex; align-content: stretch; justify-content: space-between; margin-bottom: 0.5%; }: This rule styles each row of buttons. It uses Flexbox to layout the buttons in a row, stretch them to fill the row vertically, distribute space between them, and add a small margin at the bottom.

Script.js

This script.jsfile provides the functionality for a web-based iOS-style calculator application. Here’s a breakdown of the JavaScript code:

  • runningTotal, buffer, and previousOperator are variables that store the current total, the current number being entered, and the last operator used, respectively.
  • screen is a reference to the calculator’s screen element in the DOM.
  • buttonClick(value) is called whenever a button is clicked. If the button’s value is a number, it calls handleNumber(value). If it’s a symbol (operator or other function), it calls handleSymbol(value). It then updates the screen with rerender().
  • handleNumber(value) appends the clicked number to the buffer, or replaces the buffer if it’s currently “0”.
  • handleMath(value) prepares the calculator for a math operation. It converts the buffer to an integer and stores it in runningTotal if it’s the first number, or performs the pending operation if there’s already a running total. It then sets previousOperator to the clicked operator and resets the buffer.
  • flushOperation(intBuffer) performs the operation stored in previousOperator on runningTotal and intBuffer.
  • handleSymbol(value) performs various functions depending on the clicked symbol: clear (C), calculate result (=), backspace (←), or math operation (+, -, ×, ÷).
  • rerender() updates the calculator’s screen to display the current buffer.
  • init() sets up the calculator by adding a click event listener to all the buttons. When a button is clicked, it calls buttonClick() with the button’s value.
  • init() is called at the end of the script to initialize the calculator when the page loads.

Top comments (0)