Anteriormente, le mostré cómo usar la propiedad CSS border-radius para crear la siguiente calculadora. Ahora te mostraré cómo usar jQuery para implementar la funcionalidad de la calculadora.

Añadiendo jQuery
Usaremos jQuery en este proyecto para responder a eventos cuando un usuario hace clic en un botón. Necesitamos agregar la biblioteca jQuery a nuestra aplicación. Usaré la biblioteca CDN cdnjs para agregar jQuery.
En la parte inferior de mi archivo index.html, agregaré la siguiente etiqueta de secuencia de comandos:
Operador de manejo frente a botones numéricos
Antes de escribir mi código, decidí hacer una lluvia de ideas sobre cómo manejaría la funcionalidad detrás de la calculadora. Divido los botones de la calculadora en dos grupos: operador y número .
Un botón numérico correspondería a los números del 0 al 9. Todos los demás botones son operadores.
Variables globales para nuestra operación
El siguiente paso es determinar cuántas variables globales necesitaremos. Las variables globales mantendrán la funcionalidad de nuestra calculadora. Por ejemplo, un usuario puede ingresar la siguiente secuencia:
2 + 3 = 5
Asimismo, un usuario puede ingresar esta secuencia mucho más larga:
2 + 3 * 4 / 5 - 6 = -2
Al considerar inicialmente las variables globales, podríamos considerar la creación de una nueva variable cada vez que el usuario presione una tecla. Esto no sería muy eficaz. Tendríamos que realizar un seguimiento de quién sabe cuántas variables a medida que el usuario presiona las teclas.
Para mejorar esto, podemos simplificar las cosas para que solo necesitemos cuatro variables globales:
- num1
- num2
- operador
- total
Déjame mostrarte cómo funciona esto. El primer número que presiona el usuario se almacena en la variable num1. El operador (es decir, +, -, *, / o enter) se almacena en el operador. El siguiente número ingresado se almacena en la variable 2. Una vez ingresado el segundo operador, se calcula el total. El total se almacena en la variable total.
Una pregunta lógica sería ¿qué haces con el tercer o cuarto número que ingresa un usuario? La respuesta simple es que reutilizamos num1 y num2.
Una vez calculado el total, podemos reemplazar el valor en num1 con el total. Entonces necesitaríamos vaciar el operador y las variables num2. Repasemos esto con nuestro segundo ejemplo de arriba:
2 + 3 * 4 / 5 - 6 = -2// num1 is assigned value of 2// operator is assigned value of +// num2 is assigned value of 3// total is assigned the value of 5// num1 is assigned the value of 5// num2 and operator are cleared// operator is assigned value of *// num2 is assigned value of 4// total is assigned value of 20// num1 is assigned value of 20// num2 and operator are cleared// operator is stored value of /// num2 is assigned value of 5// total is assigned value of 4// num1 is assigned value of 4// num2 and operator are cleared// operator is assigned value of -// num2 is assigned value of 6// total is assigned value of -2// num1 is assigned value of -2// num2 and operator are cleared// operator is assigned value of =
Ahora ve que podemos manejar todas las combinaciones posibles de botones presionados por el usuario usando estas 4 variables.
Obteniendo la tecla presionada por el usuario
Ahora que hemos recorrido nuestra lógica, debemos comenzar el proceso de manejo de la tecla que presionó el usuario. En la parte inferior de mi archivo index.html, crearé una etiqueta de secuencia de comandos que contendrá mi código.
El primer paso es obtener la tecla que presionó un usuario. Aquí hay un fragmento de mi archivo index.html que muestra todos los botones en una fila de la calculadora:
1 2 3 +
Cada botón, ya sea un número o un operador, se define mediante un elemento <
; / button>. Podemos usar esto para detectar cuando un usuario hace clic en un botón.
En jQuery, puede tener una función de clic de botón. Cuando se hace clic en un botón, a la función se le pasa un objeto de evento. El event.target
contendrá el botón en el que se hizo clic. Puedo obtener el valor del botón usando la innerHTML
propiedad.
Aquí está el código que consola.lográ el botón en el que un usuario hace clic.
$(document).ready(function() { $('button').on('click', function(e) { console.log('e', e.target.innerHTML); });});
Ahora, si prueba el código, verá el valor de la tecla que presiona. Esto funciona para todos los botones de la calculadora.
Creando nuestras variables globales
Ahora que tenemos la capacidad de determinar qué tecla se presionó, debemos comenzar a almacenarlas en nuestras variables globales. Voy a crear mis cuatro variables globales:
let num1 = '';let num2 = '';let operator = '';let total = '';
Botón de manejo cuando se hace clic
Cuando un usuario hace clic en un botón, estará haciendo clic en un número o un operador. Por eso voy a crear dos funciones:
function handleNumber(num) { // code goes here}
function handleOperator(oper) { // code goes here}
En mi función de clic de botón anterior, puedo reemplazar el archivo console.log con una llamada a la función apropiada. Para determinar si se hizo clic en un botón u operador, puedo comparar e.target.innerHTML
para ver si está entre 0 y 9. Si es así, el usuario hizo clic en un número. De lo contrario, el usuario hizo clic en un operador.
Este es mi paso inicial para probar y asegurarme de que puedo saber en qué botón se hizo clic:
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { console.log('number'); } else { console.log('operator'); } });});
Una vez que esté satisfecho de que estoy identificando cada botón en el que se hizo clic, puedo reemplazar el archivo console.log con una llamada a la función apropiada:
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { handleNumber(btn); } else { handleOperator(btn); } });});
Manejo de botones numéricos
Cuando un usuario presiona un número, se le asignará la variable num1 o num2. num1 tiene asignado el valor de ''
. Podemos usar esto para determinar a qué variable asignar el número. Si num1 está vacío, le asignamos el número. De lo contrario, lo asignamos a num2.
Así es como se ve mi función handleNumber:
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; }}
Manejo de botones de operador
Nuestra función para manejar cuando se presiona un botón de operador es muy simple. Todo lo que tenemos que hacer es asignar el valor a nuestra variable de operador.
Así es como se ve mi función handleOperator:
function handleOperator(oper) { operator = oper;}
Visualización de botones
The next step is to actually display the button pressed to the user. If you check out the functionality of the calculator on your phone, you will notice it only displays numbers. If a user presses the +
key, it is not displayed.
In our index.html file, we have a div with a class of 'calc-result-input'
that displays our input. We will use this to display numbers to our users.
Since we have separated out our calculator activity into functions, we will create a function to display the button.
Here is what my displayButton function looks like:
function displayButton(btn) { $('.calc-result-input').text(btn);}
Since we only update the display when the user presses a number, we can call the displayButton
function from within the handleNumber
function.
Here is what my handleNumber function looks like now:
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; } displayButton(num);}
Handling totals
The next step is to calculate a total. A total is only calculated after a user presses an operator after having a value assigned to num1 and num2.
For example, if the user enters:
2 + 3 =
We want to sum num1 and num2 and display the total.
If the user enters:
2 - 1 =
We want to subtract num2 from num1 and display the total.
We create a handleTotal
function to handle this. This function will create a total based on the operator pressed. Since there are multiple operators that can be pressed, we will use a case statement to handle them.
For simplicity’s sake, I am only going to show the code to handle when the user clicks the +
operator button.
Here is the handleTotal function:
function handleTotal() { switch (operator) { case '+': total = +num1 + +num2; displayButton(total); break; }}
Converting String to Number for calculation
When we get the innerHTML
of the button that is pressed, we get a string value. To sum two variables, they need to be converted to a number. There is a shorthand notation in JavaScript that will convert a string to a number by prefixing the variable with a +
sign. You can see where I am doing this conversion on this line:
total = +num1 + +num2;
When to call handleTotal function
Now that we have a function to calculate the total, we need to call it at the appropriate time. We only calculate total after a user enters their second operator.
To handle this we will need to make a change to our existing handleOperator
function. Previously, we were assigning the operator variable the value of the operator button the user clicked. Now we need to know if this is the first operator the user has clicked or not. We don’t calculate a total when the user clicks on the first operator.
To account for this, we can check to see if the operator variable has a value of ''
. If so, this is the first operator. If operator has a value, then we will want to calculate a total.
Here is what the handleOperator() function looks like now:
function handleOperator(oper) { if (operator === '') { operator = oper; } else { handleTotal(); operator = oper; } }
Moving Script to app.js file
Currently our HTML and JavaScript code are all contained in the index.html file. We want to split out the logic into a separate file. I create a new file called app.js
.
I copy the entire contents of the ening &l
t;script> tag and closi
ng tag in my index.html file.
The last thing we need to do is to tell our index.html file where our scripts are. We do this by adding this line below the
Final Files
Final Files
I now have these three files:
index.html
app.js
style.css
The index.html file is used to display the calculator to the user on the web page.
The style.css is used to style my calculator. Please review my previous article that talks about using the CSS border-radius property to style the calculator.
The app.js file contains the logic behind the calculator.
Here is what my app.js file looks like:
let num1 = '';let num2 = '';let operator = '';let total = '';
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { handleNumber(btn); } else { handleOperator(btn); } });});
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; } displayButton(num);}
function handleOperator(oper) { if (operator === '') { operator = oper; } else { handleTotal(); operator = oper; }}
function handleTotal() { switch (operator) { case '+': total = +num1 + +num2; displayButton(total); break; case '-': total = +num1 - +num2; displayButton(total); break; case '/': total = +num1 / +num2; displayButton(total); break; case 'X': total = +num1 * +num2; displayButton(total); break; } updateVariables();}
function displayButton(btn) { $('.calc-result-input').text(btn);}
function updateVariables() { num1 = total; num2 = '';}
Summary
Summary
Our calculator works, but only if the user clicks the
+
operator. You can add to the functionality in the handleTotal function to account for all operators. I have all the functionality in my repo which you can find here.
Further Readings
Further Readings
Breadth First Search in JavaScript — The two most common methods of searching a graph or a tree are depth first search and breadth first search. This story shows you how to use a breadth first search of a graph or a tree.
Instantiation Patterns in JavaScript — Instantiation patterns are ways to create something in JavaScript. JavaScript provides four different methods to create objects. Learn how to create all four in this article.
Using Node.js & Express.js to save data to MongoDB Database — The MEAN stack is used to describe development using MongoDB, Express.js, Angular.jS and Node.js. In this tutorial I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database.

Original text