Simple Online Calculator Created With jQuery

Simple Online Calculator Created With jQuery
File Size: 39.2 KB
Views Total: 586
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

This tutorial will show you how to create a simple online calculator that is created with jQuery.

The calculator can be used for basic arithmetic such as addition, subtraction, multiplication and division.

We'll be using HTML and CSS for styling elements on the page, while taking advantage of event listeners in JavaScript for modifying their appearance based on user interactions. Let's get started! 

How to use it:

1. Create the HTML for the calculator interface. Copy this code block and add it to your webpage.

<div class="container">
  <div class="row">
      <button id="clear" value="">AC</button>
      <div class="screen"></div>
  </div>
  <div class="row">
      <button class="digit" value="7">7</button>
      <button class="digit" value="8">8</button>
      <button class="digit" value="9">9</button>
      <button class="operation" id="/">/</button>
  </div>
  <div class="row">
      <button class="digit" value="4">4</button>
      <button class="digit" value="5">5</button>
      <button class="digit" value="6">6</button>
      <button class="operation" id="-">-</button>
  </div>
  <div class="row">
      <button class="digit" value="1">1</button>
      <button class="digit" value="2">2</button>
      <button class="digit" value="3">3</button>
      <button class="operation" id="+">+</button>
  </div>
  <div class="row">
      <button class="digit" value="0">0</button>
      <button class="decPoint" value=".">.</button>
      <button class="equal" id="eql">=</button>
      <button class="operation" id="*">*</button>
  </div>
</div>

2. Add the following CSS snippets to your CSS.

/* optional */
@font-face {
  font-family: 'Digital-7';
  src: url('./fonts/Digital-7.ttf') format('embedded-opentype'), /* Internet Explorer */
  url('./fonts/Digital-7.ttf') format('woff2'), /* Super Modern Browsers */
  url('./fonts/Digital-7.ttf') format('woff'), /* Pretty Modern Browsers */
  url('./fonts/Digital-7.ttf')  format('truetype'), /* Safari, Android, iOS */
  url('./fonts/Digital-7.ttf') format('svg'); /* Legacy iOS */
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Digital-7';
  font-weight: normal;
  font-style: normal;
}

/* calculator styles */
.container {
  border: 1px dashed black;
  min-width: 310px;
  max-width: 310px;
  margin: 10px auto;
  overflow: auto;
  padding: 10px;
  border-radius: 5px;
}

.row {
  min-width: 290px;
  max-width: 290px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.screen {
  height: 40px;
  line-height: 28px;
  width: 190px;
  text-align: right;
  border: 1px solid black;
  border-radius: 5px;
  font-size: 30px;
  padding: 6px;
}

button {
  background-color: black;
  color: white;
  font-family: inherit;
  border: none;
  width: 50px;
  padding: 5px 15px;
  margin: 5px;
  border-radius: 5px;
  cursor: pointer;
  text-decoration: none;
  font-size: 20px;
  line-height: 30px;
}

button:active {
  background-color: lightgrey;
  color: black;
}

3. The main function to enable the calculator app. Copy the JavaScript snippets and insert them after the latest jQuery JavaScript library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
var num1 = null; 
var num2 = null; 
var operator = null;
var total = 0;
var screenDisplay = '';
var numPeriod = 0;

$(document).ready(function() {
  $('#clear').on('click', function () {
    reset()
    displayScreen(total);
  });

  $('.digit').on('click', function (e) { 
    handleDigit(e);
  });

  $('.decPoint').on('click', function (e) {
    // Only add the decimal point if there is none present
    if (numPeriod == 0) {
      handleDigit(e);
      numPeriod++;
    }
  })

  $('.operation').on('click', function (e) {
    if (num1 == null) {
      return;
    } else if (num2 == null) {
      operator = e.target.id;
      displayScreen(num1 + operator);
      console.log({num1, operator, num2, total})
    } else {
      /* If both num1 and num2 are full, then push the 
      existing value to num1 and save the operator */
      num1 = compute(num1, num2);
      operator = e.target.id;
      num2 = null;
      displayScreen(num1 + operator);
      // console.log({num1, operator, num2, total})
    }
  });

  $('.equal').on('click', function (e) {
    if (num1) {
      if (!operator) {
        total = num1;
        displayScreen(num1);
        // console.log({num1, operator, num2, total})
        return;
      }
    }

    total = compute(num1, num2);
    displayScreen(total);

    operator = null;
    num1 = total;
    num2 = null;
  });
});

function compute(stringA, stringB) {
  let a = parseFloat(stringA);
  let b = parseFloat(stringB);

  switch (operator) {
    case "/":
      return (a / b).toFixed(3);
    case "-":
      return (a - b).toFixed(3);
    case "+":
      return (a + b).toFixed(3);
    case "*":
      return (a * b).toFixed(3);
    default:
      break;
  }
}

function displayScreen(text) {
  $('.screen').text(text);
  screenDisplay = text.toString();
}

function handleDigit(e) {
  if (num1 == null) {
    num1 = e.target.value;
    displayScreen(num1);
    // console.log({num1, operator, num2, total})
  } else if (operator == null) {
      num1 += e.target.value;
      displayScreen(num1);
      // console.log({num1, operator, num2, total})
  } else {
    if (num2 == null) {
      num2 = e.target.value;
      displayScreen(num1 + operator + num2);
      // console.log({num1, operator, num2, total})
    } else {
      num2 += e.target.value;
      displayScreen(num1 + operator + num2);
      // console.log({num1, operator, num2, total})
    }
  }
}

function reset() {
  num1 = null;
  num2 = null;
  operator = null;
  total = 0;
  numPeriod = 0;
}

This awesome jQuery plugin is developed by Jenguk42. For more Advanced Usages, please check the demo page or visit the official website.