Calculator App

Create The Best Basic Calculator App With JavaScript: An Easy Tutorial of 2023

Description:

In this tutorial, we’ll walk you through the process of creating a simple calculator app in JavaScript. Whether you’re a beginner or looking to refresh your coding skills, this step-by-step guide will help you build a functional calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.

With clear explanations and easy-to-follow code snippets, you’ll gain a better understanding of how JavaScript can be used to create interactive web app. Let’s get started and develop your own calculator app in no time!

  • DOM manipulation
  • Control Structures
  • Working with ForEach in JavaScript
  • JavaScript CSS manipulation
  • Working with EventListeners and events in JavaScript.

1. HTML Structure

The code begins with a standard HTML5 structure. It includes a head section that defines the document’s metadata and links a CSS style block.

Inside the body, there is a section with the class “calculator” containing a div with the class “container” and a form with an input field of type “text” and class “screen.”

<section class="calculator">
    <div class="container">
      <form>
   <input type="text" name="" id="" class="screen">
  </form>
  <div class="buttons">
   <!-- Orange Color Button -->
   <button type="button" class="btn btn-orange" data-num="*">*</button>
   <button type="button" class="btn btn-orange" data-num="/">/</button>
   <button type="button" class="btn btn-orange" data-num="-">-</button>
   <button type="button" class="btn btn-orange" data-num="+">+</button>
   <!-- grey buttons -->
   <button type="button" class="btn btn-grey" data-num=".">.</button>
   <button type="button" class="btn btn-grey" data-num="9">9</button>
   <button type="button" class="btn btn-grey" data-num="8">8</button>
   <button type="button" class="btn btn-grey" data-num="7">7</button>
   <button type="button" class="btn btn-grey" data-num="6">6</button>
   <button type="button" class="btn btn-grey" data-num="5">5</button>
   <button type="button" class="btn btn-grey" data-num="4">4</button>
   <button type="button" class="btn btn-grey" data-num="3">3</button>
   <button type="button" class="btn btn-grey" data-num="2">2</button>
   <button type="button" class="btn btn-grey" data-num="1">1</button>
   <button type="button" class="btn btn-grey" data-num="0">0</button>
   <button type="button" class="btn-equal btn-grey">=</button>
   <button type="button" class="btn-clear btn-grey">C</button>
  </div>
    </div>
 </section>

2. CSS Styling

The CSS styles defined in the style block are used to create the appearance of the calculator. It sets the margins and padding to zero, applies the box-sizing property, and centers the calculator in the middle of the viewport using Flexbox.

The calculator display (screen) has a black background, white text, large font size, and no borders. The calculator buttons are organized in a flexbox container, and various styles are applied to create the button layout and appearance.

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

body{
 min-height: 100vh;
 display: flex;
 align-items: center;
 justify-content: center;

}
.screen {
  width: 100%;
  font-size: 4rem;
  padding: 0.5rem;
  background: #000000;
  color: #ffffff;
  border: none;
}

.buttons{
 display: flex;
 flex-wrap: wrap;
 transition: all 0.5s linear;
}

button{
 flex:0 0 25%;
 border: 1px solid black;
 padding: 0.25rem 0;
 transition: all 2s ease;
}
button:hover{
 background: #000000;
 color: #ffffff;
 border: 1px solid #ffffff;
}
.btn-orange{
 background: #fcb900;
 color: #000000;
}
.btn-grey{
 background: #606060;
 color: #ffffff;
}
.btn,.btn-equal,.btn-clear{
 font-size: 4rem;
}
.btn-equal{
 background: #fcb900;
 color: #000000;
}
.btn-clear{
 background: red;
 color: #000000;
}

3. Calculator Buttons

The calculator buttons are created using the `<button>` element. There are two sets of buttons: orange buttons (btn-orange class) and grey buttons (btn-grey class).

The orange buttons represent mathematical operators (*, /, +, -), while the grey buttons represent numbers (0 to 9), decimal point (.), equal (=), and clear (C).

4. JavaScript Code

The JavaScript code for the calculator app in JavaScript is enclosed within an Immediately Invoked Function Expression (IIFE) to encapsulate the code and prevent conflicts with other scripts on the page.

calculator app

The script targets specific elements of the HTML document to add interactivity to the calculator.

5. Querying Elements

The script for the calculator app in JavaScript uses the `document.querySelector` and `document.querySelectorAll` methods to obtain references to specific elements in the HTML.

The `screen` variable holds a reference to the calculator display input field (`.screen` class), and the `buttons` variable holds references to all calculator buttons (`.btn` class). Additionally, the `clear` and `equal` variables are assigned references to the “C” (clear) button and “=” (equal) button, respectively.

    //Wrap code in an IIFE
(function(){
  
  let screen = document.querySelector('.screen');
  let buttons = document.querySelectorAll('.btn');
  let clear = document.querySelector('.btn-clear');
  let equal = document.querySelector('.btn-equal');

6. Button Click Event Listeners

The script for the “calculator app in JavaScript” sets up event listeners for all calculator buttons using a `forEach` loop on the `buttons` array. When any button is clicked, the event listener triggers a function that extracts the `data-num` attribute of the clicked button.

The value of this attribute (number or operator) is appended to the current value displayed in the calculator’s screen input field.

buttons.forEach(function(button){
    button.addEventListener('click', function(e){
      let value = e.target.dataset.num;
      screen.value += value;
    })
  });

7. Equal Button Event Listener

An event listener is also set up for the “=” (equal) button. When clicked, it checks if the calculator display is empty.

If it is, it displays the message “Please Enter a Value.” Otherwise, it evaluates the mathematical expression in the calculator app display using the `eval()` function and stores the result in the `answer` variable. The result is then displayed in the calculator’s screen input field.

equal.addEventListener('click', function(e){
    if(screen.value === ''){
      screen.value = 'Please Enter a Value';
    } else {
      let answer = eval(screen.value);
      screen.value = answer;
    }
  })

8. Clear Button Event Listener

Another event listener is set up for the “C” (clear) button. When clicked, it resets the calculator display to an empty state by setting its value to an empty string.

clear.addEventListener('click', function(e){
    screen.value = '';
  })

9. End of Script for the calculator app

The IIFE (Immediately Invoked Function Expression) is immediately invoked at the end of the JavaScript code, ensuring that the event listeners for the calculator app in JavaScript are set up when the page loads.

})(); //end IIFE

Conclusion

In summary, the provided code creates a simple calculator app with a responsive layout using HTML, CSS, and JavaScript. Users can input numbers and perform basic arithmetic operations, and the calculator displays the results on the screen.

If you find additional information, please refer to this article on Create The Best Basic Calculator App With JavaScript.makeuseof.

If you seek further information about Create The Best Basic Calculator App With JavaScript or have any inquiries regarding our blog, please don’t hesitate to contact us via email at info@thinkwriteway.com

calculator app

Share This Article :

Leave a Comment

What to read next