Develop calculator example code using native javascript

Develop calculator example code using native javascript

The main function of a calculator is to perform numerical calculations. Developing a web instance of the calculator function will help you better master the basic numerical calculation capabilities of js.

This example analyzes in detail the development steps of a js calculator. It is best to have some basic js knowledge when studying this tutorial.

The calculator consists of two parts: the number display area and the button area. First, write the HTML elements of these two areas of the calculator, as shown below:

<div class="calculator_wrap" id="calculator"><!--Calculator outsourcing element-->
 <div class="show_num"><!--Show number area-->
 <div class="num_save" id="numSave"></div><!--Calculation formula-->
 <div class="num_cur" id="numCur">0</div><!--Calculation result-->
 <div class="show_m" id="showM">M</div><!--Memory storage logo-->
 </div>
 <div class="btn_wrap" id="btnWrap"><!--Button area-->
 <div class="btn" data-key="MC">MC</div><!--Memory clear-->
 <div class="btn" data-key="MR">MR</div><!--Memory Reading-->
 <div class="btn" data-key="MS">MS</div><!--Storage Memory-->
 <div class="btn" data-key="MA">M+</div><!--Memory plus-->
 <div class="btn" data-key="ML">M-</div><!--Memory reduction-->
 <div class="btn" data-key="BACK">←</div><!--Backspace-->
 <div class="btn" data-key="CE">CE</div><!--Clear current-->
 <div class="btn" data-key="Clear">C</div><!--Clear-->
 <div class="btn" data-key="Negate">±</div><!--Positive and negative conversion-->
 <div class="btn" data-key="Square">√ ̄</div><!--Square root-->
 <div class="btn" data-key="Num" data-value="7">7</div><!--7-->
 <div class="btn" data-key="Num" data-value="8">8</div><!--8-->
 <div class="btn" data-key="Num" data-value="9">9</div><!--9-->
 <div class="btn" data-key="Base" data-value="/">/</div><!--Except-->
 <div class="btn" data-key="Percentage">%</div><!--Percent sign-->
 <div class="btn" data-key="Num" data-value="4">4</div><!--4-->
 <div class="btn" data-key="Num" data-value="5">5</div><!--5-->
 <div class="btn" data-key="Num" data-value="6">6</div><!--6-->
 <div class="btn" data-key="Base" data-value="*">*</div><!--Multiply-->
 <div class="btn" data-key="Reciprocal">1/x</div> <!--Countdown-->
 <div class="btn" data-key="Num" data-value="1">1</div><!--1-->
 <div class="btn" data-key="Num" data-value="2">2</div><!--2-->
 <div class="btn" data-key="Num" data-value="3">3</div><!--3-->
 <div class="btn" data-key="Base" data-value="-">-</div><!--Minus-->
 <div class="btn equal" data-key="Equal">=</div><!--Equal-->
 <div class="btn zero" data-key="Num" data-value="0">0</div><!--0-->
 <div class="btn" data-key="Point">.</div><!--Decimal point-->
 <div class="btn" data-key="Base" data-value="+">+</div><!--Add-->
 </div>
</div>

Readers can write some styles by themselves and design a calculator effect they like. The calculator effect of this example is shown in the figure below:

Style code:

.calculator_wrap{width:240px;height:360px;padding:10px;margin:30px auto;border:1px solid #8acceb;background:#d1f1ff;}
 .calculator_wrap .show_num{position:relative;padding:0 8px;height:60px;background:#fff;text-align:right;}
 .calculator_wrap .show_m{position: absolute;left:10px;bottom:3px;display:none;}
 .calculator_wrap .num_save{height:26px;line-height:26px;font-size:12px;white-space:nowrap;}
 .calculator_wrap .num_cur{font-size:28px;height:34px;line-height:34px;}
 .calculator_wrap .btn_wrap{font-size:0px;}
 .calculator_wrap .btn{display:inline-block;width:38px;height:38px;line-height:38px;text-align:center;border:1px solid #ccc;background:#666;color:#fff;font-size:14px;margin:10px 10px 0 0;cursor:pointer;}
 .calculator_wrap .btn:hover{background:#333;}
 .calculator_wrap .btn:nth-child(5n){margin-right:0px;}
 .calculator_wrap .equal{position:absolute;height:90px;line-height:90px;}
 .calculator_wrap .zero{width:90px;}

For a novice, the calculator functions may seem complicated, with so many buttons and multiple calculation methods, it may be hard to know where to start. In fact, for any function, you just need to sort out your ideas and write code step by step, and you will find that it is not difficult to implement.

1 Get each HTML element

No matter what the web front end wants to do on the page, it must first obtain the DOM elements on the page. It seems that the entire calculator has many buttons. In actual development, event delegation can be used to operate buttons, so only the container element of all buttons needs to be obtained. The code is as follows:

//Get the outsourced element var eCalculator = document.getElementById('calculator');
//Save calculation data (formula) container var eNumSave = document.getElementById('numSave');
//Current digital container var eNumCur = document.getElementById('numCur');
//Button external container, used for event proxy var eBtnWrap = document.getElementById('btnWrap');
//Memory storage flag element var eShowM = document.getElementById('showM');

2 Declare related variables

During the calculation process, some variables are needed to assist in calculation, store results and make judgments, as shown below:

//Calculation formula var sStep = '';
//Current number var sCurValue = '0';
//Calculation result var nResult = null;
//Operator var sMark = '';
//MR memory storage data var nMvalue = 0;
//Input status. false: input number to replace the original number; true: input number to add to the original number;
var bLogStatus = false;

3. Add click events to buttons

Because the entire calculator has many buttons, binding an event to each button individually would be too much, cumbersome, and would affect performance and be prone to errors. So just now we only got the external container eCalculator of the button.

When using event delegation, you only need to add a click event to the container, determine which button is currently clicked, and then perform the corresponding calculation. When you click a button with the mouse, you may select the text on the button because you click too quickly. Therefore, you also need to add an operation to the outer container to prevent the default behavior. The code is as follows:

//Outsourcing container adds mouse down event to prevent text from being selected eCalculator.addEventListener('mousedown',function(event){
 //Prevent the default behavior when the mouse is pressed to prevent the text from being selected when the button is clicked too quickly event.preventDefault();
});

//The button container adds a click event to proxy all button operations eBtnWrap.addEventListener('click',function(event){

});

3.1 Get the clicked button and value

The element clicked by the mouse can be obtained through the event parameter passed into the event function. Then use the data-key and data-value attributes on the element to determine which button the mouse clicked and its value, as shown below:

eBtnWrap.addEventListener('click',function(event){
 //Get the clicked element var eTarget = event.target;
 //Judge the pressed key var key = eTarget.dataset.key;
 //Get the pressed value var value = eTarget.dataset.value;
});

3.2 Determine the key and value, and perform input operations using numeric keys and decimal points

If the key attribute data-key is 'Num', it means that a number is pressed, and 'Point' means a decimal point.

These keys are all used to execute input. Since there are multiple numbers, the number input is encapsulated in the fnInputNum function. Then encapsulate the fnShowResult function to display the data in the display digital area. As shown below:

eBtnWrap.addEventListener('click',function(event){
 /* … */

 //Determine if the button is clicked if(key){
 //Use the switch statement to determine the corresponding operation of different buttons switch(key){
  //Number keys to perform operations case 'Num':
  fnInputNum(value);
  break;
  //Decimal point operation case 'Point':
  //Judge whether there is a decimal point to limit the input of only one decimal point if(sCurValue.indexOf('.')==-1){
   sCurValue = sCurValue + '.';
   bLogStatus = true;
  }
  break;
 }
 //Display data to the display number area fnShowResult();
 }
});
//Input number function fnInputNum(num){
 //Determine whether to replace the current number or add it to the back of the current number based on the input status if (bLogStatus) {
 sCurValue = sCurValue + num;
 }else{
 //Limit the first number to not be 0
 if(num!=0){
  bLogStatus = true;
 }
 sCurValue = num;
 }
}
//Show calculation results function fnShowResult(){
 //Display calculation formula eNumSave.innerHTML = sStep;
 //Limit the total length of numbers if(sCurValue.length>14){
 sCurValue = sCurValue.slice(0,14);
 }
 //Display the current number eNumCur.innerHTML = sCurValue;
}

At this point, you can click on numbers and decimal points to enter them on the calculator display, as shown in the figure:

3.3 Addition, subtraction, multiplication and division

The most basic operations of a calculator are addition, subtraction, multiplication and division. In order to implement the functions of adding, subtracting, multiplying and dividing numbers and calculating the results, the three functions fnCountResult, fnBaseCount and fnEqual are encapsulated.

fnCountResult is used to calculate the result according to the operator;

fnBaseCount modifies the calculation formula or calculation result;

fnEqual is used to calculate the result and reset the data when the = sign is pressed. As shown below:

eBtnWrap.addEventListener('click',function(event){
 /* … */

 //Determine if the button is clicked if(key){
 //Use the switch statement to determine the corresponding operation of different buttons switch(key){
  /* … */
  //Basic operations of addition, subtraction, multiplication and division case 'Base':
  fnBaseCount(value);
  break;
  // case 'Equal':
  fnEqual();
  break;
 }
 //Display data to the display number area fnShowResult();
 }
});
//Calculation result function fnCountResult(){
 //Judge the current operator and perform the operation switch(sMark){
 case '+':
  nResult = nResult===null?+sCurValue:nResult + (+sCurValue);
  break;
 case '-':
  nResult = nResult===null?+sCurValue:nResult - sCurValue;
  break;
 case '*':
  nResult = nResult===null?+sCurValue:nResult * sCurValue;
  break;
 case '/':
  nResult = nResult===null?+sCurValue:nResult / sCurValue;
  break;
 default:
  nResult = +sCurValue;
 }
}
//Basic operations of addition, subtraction, multiplication and division function fnBaseCount(key){
 //If it is input status, perform calculation if(bLogStatus){ 
 //Modify input status bLogStatus = false;
 //Calculation formula sStep = sStep + ' ' + sCurValue + ' ' + key;
 //Calculation results fnCountResult();
 sCurValue = ''+nResult;
 }else{
 //If the formula is empty, add the original number first if(sStep==''){ 
  sStep = sCurValue + ' ' + key;
 }else{ //If there is an existing formula, change the last operator sStep = sStep.slice(0,sStep.length-1) + ' ' + key;
 }
 }
 //Change the operator to calculate sMark = key;
}
//Equal to function fnEqual(){
 //If there is no operator, prevent subsequent operations if(sMark=='')return;
 //Calculation results fnCountResult();
 sCurValue = ''+nResult;
 //Reset data sStep = '';
 sMark = '';
 bLogStatus = false;
}

Now you can do addition, subtraction, multiplication and division on the calculator, as shown in the figure:

3.4 Add operations to other buttons. The code is as follows:

eBtnWrap.addEventListener('click',function(event){
 /* … */

 //Determine if the button is clicked if(key){
 //Use the switch statement to determine the corresponding operation of different buttons switch(key){
  /* … */

  // Clear case 'Clear':
  fnClear()
  break;
  //Backspace case 'BACK':
  fnBack();
  break;
  //CE
  case 'CE':
  // Clear the current displayed value sCurValue = '0';
  bLogStatus = false;
  break;
  // Negate case 'Negate':
  //Current value inverted sCurValue = ''+(-sCurValue);
  break;
  // Take the square root case 'Square':
  //Take the square root of the current value nResult = Math.sqrt(+sCurValue);
  //Other data initialization sCurValue = ''+nResult;
  sStep = '';
  sMark = '';
  bLogStatus = false;
  break;
  //Countdown case 'Reciprocal':
  //Get the inverse of the current value //Other data initialization nResult = 1/sCurValue;
  sCurValue = ''+nResult;
  sStep = '';
  sMark = '';
  bLogStatus = false;
  break;
  //M series case 'MC':
  // Clear the memory value nMvalue = 0;
  fnShowM()
  break;
  case 'MR':
  //Display memory value sCurValue = '' + nMvalue;
  fnShowM()
  break;
  case 'MS':
  //Change the memory value to the current value nMvalue = +sCurValue;
  fnShowM()
  break;
  case 'MA':
  //Add the current value to the memory value nMvalue += +sCurValue;
  fnShowM()
  break;
  case 'ML':
  //Subtract the current value nMvalue -= +sCurValue from the memory value;
  fnShowM()
  break;
 }
 //Display data to the display number area fnShowResult();
 }
});
//Clear function fnClear(){
 //Initialize all data sStep = '';
 sCurValue = '0';
 nResult = null;
 sMark = '';
 bLogStatus = false;
}
//Backspace function fnBack(){
 //You must be in input mode to backspace if (bLogStatus) {
 //Subtract the last digit of the value sCurValue = sCurValue.slice(0,sCurValue.length-1);
 //If the last value is empty or negative (-), change it to 0, reset the input state to false, and no backspace is allowed if (sCurValue==''||sCurValue=='-'){
  sCurValue = '0';
  bLogStatus = false;
 }
 }
}
//Judge whether there is M memory storage function fnShowM(){
 bLogStatus = false;
 //Judge whether to display the memory storage mark eShowM.style.display = nMvalue==0?'none':'block';
}

4 Binding keyboard events

Having written this, the calculator can be used normally. However, it is not efficient to just click the buttons with the mouse. In order to use the calculator faster, you also need to add keyboard events. When the corresponding button is pressed, the operation is performed, as shown below:

//Keyboard event document.addEventListener('keyup',function(event){
 //Get the current keyboard key var key = event.key;
 //Get the key code
 var code = event.keyCode;
 //Limit the correct keystrokes to modify the displayed data var comply = false;
 //Input numberif((code>=48&&code<=57)||(code>=96&&code<=105)){
 fnInputNum(key);
 comply = true;
 }
 //Addition, subtraction, multiplication and divisionif( key=='*'||key=='+'||key=='/'||key=='-'){
 fnBaseCount(key);
 comply = true;
 }
 //esc keyif(code==27){
 fnClear();
 comply = true;
 }
 //Enter keyif(code==13){
 fnEqual();
 comply = true;
 }
 //Backspace keyif(code==8){
 fnBack();
 comply = true;
 }
 if(comply){
 //Display data to calculator screen fnShowResult();
 }
});

A simple calculator is now completed. If the purpose is to learn, it is recommended not to copy the code directly. It is best to manually enter the code and comments to deepen the impression and improve the learning effect.

Summarize

This is the end of this article about using native javascript to develop a calculator. For more relevant content about developing a calculator using native js, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A simple calculator written in javascript, with a lot of content and practical methods. Recommended
  • Simple js code to realize calculator operation
  • js implements a simple calculator
  • HTML+JS implements simple calculator code (addition, subtraction, multiplication and division)
  • Simple calculator implementation code written in JS
  • javascript-simple calculator implementation step decomposition (with pictures)
  • Pure javascript code to implement calculator functions (three methods)
  • js implements a simple calculator
  • Web calculator A JS calculator
  • Simple implementation of js web calculator

<<:  A brief discussion on MySQL index design principles and the differences between common indexes

>>:  How to make a centos base image

Recommend

Create a movable stack widget function using flutter

This post focuses on a super secret Flutter proje...

Detailed explanation of this pointing in JS arrow function

Arrow function is a new feature in ES6. It does n...

JS realizes simple picture carousel effect

This article shares the specific code of JS to ac...

CentOS server security configuration strategy

Recently, the server has been frequently cracked ...

Analysis and practice of React server-side rendering principle

Most people have heard of the concept of server-s...

Markup language - CSS layout

Click here to return to the 123WORDPRESS.COM HTML ...

Linux sftp command usage

Concept of SFTP sftp is the abbreviation of Secur...

Detailed explanation of the pitfalls of mixing npm and cnpm

Table of contents cause reason Introduction to NP...

In-depth understanding of Mysql logical architecture

MySQL is now the database used by most companies ...

Detailed explanation of keywords and reserved words in MySQL 5.7

Preface The keywords of MySQL and Oracle are not ...

How much data can be stored in a MySQL table?

Programmers must deal with MySQL a lot, and it ca...

Detailed explanation of MySQL clustered index and non-clustered index

1. Clustered Index Table data is stored in the or...

Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading

Use the Vue-Cropper component to upload avatars. ...