JavaScript — создаем калькулятор
Обзор посвящен созданию JavaScript-калькулятора. Домашнее задание для каждого начинающего JavaScript-ниндзя! ) В коде используется не чистый JavaScript, а JavaScript + jQuery.
Пример и материал не является оригинальным, основан на зарубежном источнике. Указывать источник не буду, потому что это не имеет смысла — таких кратких видеоуроков просто огромное количество — выбирай любой, какой понравится. )
HTML разметка
HTML-разметка для будущего калькулятора основана на HTML-элементах , , . Ничего сверхестественного в ней нет.
Единственный момент — вопрос компоновки кнопок, куда правильно “засунуть” кнопки с арифметическими операциями:
CSS стили
Со стилизацией будущего калькулятора тоже проблем не должно возникнуть. Я использовал flexbox для выравнивания кнопок:
JavaScript код
Переходим к самому интересному — созданию JavaScript-кода для калькулятора. В своем примере я использовал JavaScript + jQuery.
Последний применил только из-за удобства манипуляции с DOM. Недавно узнал о существовании библиотеки Underscore.js как альтернативы jQuery, но меньшего размера. Надо опробовать Underscore.js обязательно! )
Первым делом инициализируем кнопки калькулятора. Для этого забираем значения из атрибута кнопок и динамически вставляем в HTML-разметку:
Исходный вид калькулятора подготовили — он теперь выглядит как настоящий калькулятор! Если не принимать во внимание кошмарных цветов и их сочетания ) Ну мы не дизайнеры, нам простительно )
Теперь стоит задача — при нажатии на кнопку калькулятора чтобы ее значение появлялось в окошке последнего. Тоже ничего сложного, если подумать.
Просто нужно забрать у активной кнопки значение ее атрибута и передать как значение элемента .
Небольшая тонкость здесь — нужно конкатенировать текущее значение элемента с текущим значением элемента ; иначе будет происходить простое замещение предыдущего значения элемента текущим значением элемента :
Полная очистка экрана калькулятора элементарно проста — достаточно при нажатии на соответствующую кнопку передать в элемент пустое значение:
Дальше уже немного интереснее — будем оживлять кнопку . То есть — ввели в окошко калькулятора, к примеру, . По нажатии на кнопку в окошке должен появиться результат этой арифметической операции.
На помощь приходит функция JavaScript под названием . На javascript.ru эта функция подробно расписана.
В результате код для “оживления” кнопки будет выглядеть “скромно”:
Наш калькулятор почти готов. Осталось добавить жизни к двум последним кнопкам — возведения в степень и посимвольной очистки экрана калькулятора.
Для возведения в степень воспользуемся стандартной JavaScript-библиотекой и ее методом .
Заберем у элемента его текущее значение и передадим в качестве одного из аргументов в метод . Второй аргумент в нашем случае — это константа 3:
Последний шаг к успеху создания калькулятора — это “оживление” кнопки посимвольной очистки экрана калькулятора.
В этом случае воспользуемся стандартным методом JavaScript — . Это метод JavaScript(), который извлекает из строки подстроку и возвращает ее в виде новой строки — почитать с примерами.
В качестве аргументов принимает два параметра — начальную и конечную позицию, которые выступают как начальный и конечный индекс массива. Массивом в данном случае является строка.
Функция (на кнопке посимвольной очистки) в нашем случае будет работать так — забираем у элемента его текущее значение. Значение возвращается в виде строки, конечно.
Поэтому находим ее длину ( ) и укорачиваем на один (последний) символ — . Таким образом мы динамически укорачиваем текущее значение в окне калькулятора на один символ.
Затем нам нужно заменить текущее значение окна калькулятора укороченным на один символ значением. Для этого берем метод и с помощью него “обрезаем” текущую строку; этот метод возвращает “обрезанный” вариант. Нам осталось только вставить его в окно калькулятора.
Результат будет выглядеть таким образом:
Вот наш калькулятор и готов — ниже полный JavaScript-код:
Конечно, примеры кода из этой статьи хоть и не являются укороченными, но не дают полного представления о разрабатываемом нами калькуляторе.
Поэтому привожу ссылку на готовый вариант калькулятора, который создавался в этой статье. На CodePen можно его посмотреть и разобрать детально (при желании).
Как вариант для сравнения, можно взглянуть на более сложный пример создания калькулятора, на чистом JavaScript. Пример был найден мною на просторах CodePen.
Заключение
Рассмотренный в статье пример лично для меня оказался на удивление прост — я ожидал большей (и более запутанной) кучи кода.
На этом все. В дальнейшем буду продолжать флудить на тему JavaScript, ибо для себя с удивлением обнаружил, что мне в последнее вермя доставляет удовольствие разбирать и рассматривать готовые примеры на JavaScript.
Единственное, что меня огорчает — тот факт, что они чужие )
Красивая функция trackBy
Пример красивой функции trackBy для Angular. Функция понравилась своей лаконичностью:<% highlight typescript %>public trackByNumber = (_. … Continue reading
Как сделать простой калькулятор на HTML и Javascript
Я знаю, что похожие вопросы задали ранее. Но всё-таки мне хотелось бы узнать, можно ли написать функцию для калькулятора, опираясь на код, мной написанный до сих пор.
Знаю, как сделать простейший калькулятор для сложения эксклюзивно:

До сих пор, нет сомнений. Но сейчас, мне хотелось бы заменить статичный знак плюса (+) четырьмя кнопками для всех базовых операций: сложения (+), вычитания (-), умножения (x), деления (:).
Интерфейс и распределения кнопок умею вставить, но не успеваю создать функцию, которая изменяет оператор в переменной result в зависимости от избранной кнопки операции.
Нужно ли делать отдельную функцию для каждой кнопки операторов? Или можно вставить всю программу в функцию кнопки выполнения («равняется. «)?
JavaScript DOM Tutorial – How to Build a Calculator App in JS

Spruce Emmanuel

You’re going to spend a lot of time working on webpages when using JavaScript. In fact, while you’re using JavaScript, the webpage is where all the exciting and important stuff takes place.
A webpage is one big document for a JavaScript developer since every element on the page is connected (like a big family). It’s all made up of parents (parentNodes) and children (childNodes). The Document Object Model is the name of this family (DOM).
In this article, you’ll learn about the DOM along with loops and events by building a simple iOS calculator app.
Table of Contents
Prerequisites
So, what are you going to need to make the most of this tutorial?
You’ll need a browser, a text editor (Vscode), and some basic JavaScript knowledge. For a head start, I recommend checking out one of these great introductory courses.
You can also read this great article on JavaScript Fundamentals.
If you’ve already read the article and participated in the challenge, here’s my simple solution.
This article also assumes you have a basic understanding of HTML and CSS, as well as how the web works.
With that, let’s dive in.
What is the DOM?
The Document Object Model (DOM) is a logical structure that defines how elements in a document can be manipulated and changed. Because the DOM is a structured this way, it is commonly referred to as a tree in which everything is connected.
Here’s an example:
You can access, modify, delete, or add new elements or content to a document using the DOM. In summary, the DOM allows you to manipulate almost everything on a webpage.
Roll up your sleeves and let’s get right to work now that we have a better understanding of what the DOM is.
How to Select Elements in the DOM
One of the very first things you’ll do when working with the DOM is to select elements in the document.
In fact, you must first learn how to access elements in the DOM before you can manipulate it.
You can select (or access) elements in a few different ways. Below, we’ll go over the few that you’ll need the most.
How to Select DOM Elements by ID
With getElementById(), you may select any element on a webpage that has an id . All you need to do is pass in the id of the element you wish to select.
Here’s the JavaScript:
It is important to remember that the getElementById method only selects the first element on a page if there are many items with the same id. Note that an id should be unique and you should never have multiple elements with the same id.
And here’s the JavaScript:
How to Select DOM Elements by Class Name
You can use the getElementsByClassName method to select any element that has a class:
Keep in mind that it says getElements – Elements with an «s». This indicates that all items with the class btn will be selected by the selector, and they will all be added to an HTMLCollection (an array). You do remember what an array is, don’t you?
How to Select DOM Elements by Tag Name
This works in a similar way to getElementsByClassName : it returns an HTMLCollection of all the Tags found in the document.
How to Select Elements by Using CSS Selectors
Here are my favorite selectors: querySelector() and querySelectorAll() . With these selectors, you can select any element in the DOM the same way you’d select any element with CSS
You use querySelector() to select a single element. If the selector matches many elements on the page, just the first one is returned.
querySelectorAll() , on the other hand, will select all the items in the document that match the selector and store them in a NodeList (an array) similar to the ones seen above.
It’s worth noting that when you use document.querySelector() , you’re searching the whole document for the element. But when you perform element.querySelector() , you’re only searching the selected element.
Consider the following example: querySelector() . The selector will only look for items that match within the element.
The form.querySelectorAll() will only select the buttons within the form. This also applies to all elements and selectors.
How to Create and Add Elements to the DOM
After learning how to select HTML elements that have already been created in the DOM, let’s try creating our own elements using JavaScript.
There are a few steps to take in order to add elements to the DOM using JavaScript. We’ll go over each of them below.
How to Create a DOM Element
JavaScript requires that any element be created before it can be added to the DOM. For this, we use the document.createElement() method.
We just created the above tags in JavaScript and have not yet added them to the DOM. Nonetheless, they are still simply tags with no attributes or text content, so let’s correct that right away.
How to Set Attributes of Elements
To set the attributes, such as adding a class, changing the ID, or changing the SRC, we simply use the setAttribute() method on the new element.
The setAttribute(«attribute», «value») method takes two parameters, the attribute and the value to be applied to the attribute.
How to Add the Text Content
Some of our newly created elements still require text to be added to them in order for us to use them in the document – even after attributes have been added.
To create the texts and add them to our newly created elements, use the method createTextNode() .
And from here, we can actually add the newly created element to the DOM.
How to Add Elements to the DOM
The sole way to add newly created elements to the DOM is by inserting them into an existing element.
The new element will be added as a child to the already selected existing element using the appendChild() method.
There are, of course, more ways to add new elements to the DOM, but I’ll leave them for your own reading.
How to Modify Elements in the DOM
In addition to creating and adding elements to the DOM, JavaScript also allows us to modify already-existing DOM elements. We can change their contents, add or remove attributes, or even change their styles.
How to Modify Text
Use textContent or innerText to modify the text of any element. See the example below:
Aside from text we can also modify attributes.
How to Modify Attributes
You can use the setAttribute() method to change any attribute that an element may have had in addition to adding new ones, as we have already seen in a previous section.
Since we’re talking about changing attributes, we can also add, delete, and toggle between adding and deleting a class attribute to an element using the classList.add() , classList.remove() , and classList.toggle() methods, respectively.
How to Modify Element Styles
You may change the styles of elements directly in JavaScript. Simply select the element and add the style property followed by the CSS style you want to use.
You can add any CSS style you want. The main difference is that CSS properties are separated by hyphens (-), for example, background-color . But in JavaScript CSS properties are written in camelCase – backgroundColor .
How to Remove Elements from the DOM
Whatever can be created can also be deleted, including elements in the DOM. For example, you can remove the child of a parent element by using removeChild() . Similarly, you can remove the p element in the div below by using removeChild() :
Above we selected the parent element and then removed the child. You can also just remove the p directly by using remove() .
It is entirely up to you how you delete elements.
Loops and Iterations
Loops let us accomplish repeated tasks, such as printing a number numerous times or iterating through an array.
With loops, we can access every item in an array, as seen in the example below, where we print out all the elements in an array.
The code above would print out every item in the array until it reaches the last one when you execute it.
But what if we wanted to stop at a certain point? You can use the break statement to exit a loop. For instance, we might decide to stop printing the elements in that array when we reach the fifth one.
The break statement terminates the loop’s execution.
You see, many years ago, the for loop (the loop above) was a great method to iterate over items in an array. But since the world and JavaScript have changed, we now have fancier and quicker ways to iterate over arrays. Now we’re going to explore the most common ones.
How to Use the forEach() and map() Methods
The forEach() method is one of the new fancy ways of looping over arrays. The forEach() method will loop through the array and run a function that you define for each item in the array.
It’s even shorter when you’re using arrow functions:
The function you provide must take at least a one parameter which is the current item in the array. The other two parameters are optional: the index (the current item’s index, which is a number) and the last parameter is the original array that you’re looping through.
The only difference between Array.map() and Array.forEach() is that Array.map() will return a new array after the callback function, whereas Array.forEach() does not return any. Array.map() will do exactly what Array.forEach() will do, which is execute a function for each item in the array.
In contrast to the for loop, the break statement is ineffective in the Array.forEach() and Array.map() methods.
The for. of Loop
The for. of loop, which accepts a variable and the array you want to iterate over, is one of the new fancy ways we may loop over any iterable item.
Just like in a regular loop, the break statement can be used in a for. of loop.
DOM Events
Users will engage in a variety of actions when using your application, such as clicking buttons, hovering over items on the screen, submitting forms, refreshing pages, and other activities that users enjoy.
In JavaScript, all of these user interactions are referred to as Events.
There are many events in JavaScript, thus it contains event listeners that may be used to respond to each one. However, we’re only going to talk about the most typical ones in this post.
| Event | Description |
|---|---|
| click | When a user clicks an element, this event is triggered. |
| mouseover | Hovering over elements in the DOM causes this event to be triggered. |
| input | When the value of an input or select element changes, this event is fired. |
| submit | When a form is submitted, this event is triggered |
| keydown | When a keyboard key is pushed, the keydown event is triggered. |
| Keyup | Fired when a pushed key is released. It is the opposite of Keydown. |
| DOMContentLoaded | This event is fired when the DOM has loaded, but this event is fired before any external resource(like css and images) is downloaded. |
| load | On the other hand, this event won’t be triggered until all DOM elements, including external resources, have loaded. |
There are many other events in JavaScript, but we’ll stop here. You can view additional events in the MDN DOM event reference.
Now that we’ve seen several types of events, let’s see how we might respond to them.
JavaScript Event Handling
The addEventListener method is the recommended way to handle events in JavaScript. This method allows you to define a function that will be executed whenever the event you specify is triggered.
The function you pass into the addEventListener() method will accept one argument: a reference to the Event Object, which has a set of properties that describe the event that just happened.
You can also remove an event listener from an element using the removeEventListener() . This method must take the exact same function as the one you passed into the addEventListener() method.
And for now that’s all for events and event handling. Enough of the talk, let’s practice all we’ve be learning so far.
How to Build the Calculator App
We’re going to build the basic iPhone calculator to put our new JavaScript skills to the test. To get started, create an HTML file, a CSS file, and then a JavaScript file.
By now, I assume you know how to set up a basic environment using those three tools. You may use an online code editor like CodePen, which is what I’ll be doing in this lesson, if you don’t have access to a PC where you can generate those files.
We’ll begin by building the foundation of our application. Open the HTML file you prepared and paste the following code into it.
As you can see above, our calculator is basically an HTML form with a lot of buttons and an input field. To style it, let’s add some CSS so that it resembles the calculator on iPhones. Open the CSS file you made and add the following code:
And now, we have a simple calculator application with no functionality at this time. This is how the live preview appears:
From the example above, whenever you click a button, the form is submitted and the page is reloaded. But we don’t want that to happen.
If you recall from the Events section, we discussed the submit event that is fired whenever we submit a form. We can use that event to stop our form from submitting whenever we click a button.
To do this, open the JavaScript file you created and add the following code:
If you return to the HTML code above and pay close attention, you will see that each button has a value property and a data-type attribute that is either operator or operand:
The reason for this is so that we can distinguish between numbers (operands) and operators when selecting buttons in JavaScript.
How to Add Functionality to the Calculator
Now that we’ve done this, we can begin adding functionality to our application.
To begin, let’s display the values of our operands when we click on the buttons. Add the following code to your JavaScript file.
Instead of selecting all the buttons one after the other (which is tedious by the way) we used the querySelectorAll() . This will select all the buttons we specified and put them in a NodeList (an array with node items).
If you remember what we discussed in the Loops and Iteration section, you cannot access any of those selected buttons unless you iterate over the array using one of the loop methods we discussed in that section.
Lastly we added a click event listener to each button like this:
Now, whenever we click on any operand value, the value of that number is displayed on the calculator.
In the else..if statement, we check if there is a decimal in our output value. If there is, we simply stop adding any further decimal point by replacing it with an empty string.
Another else..if statement checks to see whether we’ve previously clicked on an operator button. If we have and then click on an operand button, we want to set the is_operator value to false and restart the value in the output from the new value.
Here is the live preview of the example above:
Now let’s also select the buttons with data-type operator and specify what will happen whenever we click on any of the buttons.
Open your JavaScript file and add the following code:
The first thing we do in the code above, after adding a click event listener to our button, is add the class active to any operator buttons that we click. We have previously defined the styling for this active class in our CSS.
We want to apply those styles on the button we just clicked whenever we press the operator button.
We could have used an if..else statement here as well, but who says we can’t try new things? The switch statement that follows is a conditional statement in JavaScript, much like the if statement we have been seeing.
The switch statement accepts a value (the condition), in this example the value of the button that was clicked. For each case, the value is checked. In the first case a % simply converts the number in the output to a percentage.
If it were the invert button, we would simply «invert» the output result by multiplying it by «-1.»
If the = button was clicked, we add the last value from the output value to our equation array, use eval() to quickly evaluate every equation there, and then clear the equation array.
NOTE: eval() is a dangerous function. It can execute code when passed as input, and users can use it to write malicious code that can be dangerous. Only use ever when you trust the source of input that will be provided.
The code in the default runs when any other operator button that is not one of those we listed before is clicked. In the default first, we obtain the last item in the array by using this code:
Then, if the previous button we clicked was an operator—that is, if it was one of the following: / , * , + , or — —we simply delete it from the equation using equation.pop() and add the new one we clicked with equation.push() .
If our last array item was not an operator, we add the output value and the value of the button we clicked to the equation array.
Lastly we also set the value of is_operator to true anytime we click on any operator button:
You’ll notice that for each case we pass in the break statement. The break statement here will stop the execution of the switch anytime a case is true and the code finishes executing.
And there you have it – a fully functional calculator application! And here’s the live preview:
Before we finish, there is one little issue with our calculator: the active class we added to our operator buttons when clicked remains active even after we click another button.
Let’s remedy that by creating a function that removes the active from any operator button.
Now we simply need to call this function before adding the active class to any button.
We also need to remove the active class from the operators whenever an operand button get’s clicked.
Now that’s much better. You can find the full code and live preview of our app in the pen below:
JavaScript Challenge
Despite the fact that our calculator app is now completely working, there are a few functionalities that I did not include that I believe would be a wonderful opportunity for you to practice your new JavaScript skills.
- The clear button: When we click on any operand button, the value of the button should change from AC to C. When this button is clicked, we clear the form and remove any active class from our operator buttons.
- The iPhone calculator only allows a maximum of 9 numbers as operands. You cannot surpass this limit, which I believe would be a useful feature for our calculator software as well.
- Commas are automatically appended to numbers in the output of the iPhone calculator, and our program does not currently have this capability.
- If we use two decimal operands, sometimes the result is affected by a floating point rounding error. Our calculator app is not handling any rounding at the moment. Check out this article if you want to learn more about this topic.
Do you believe you can complete any of these challenges? Good luck!
Conclusion
Congratulations, JavaScript whiz! You’ve made it this far. In this tutorial, we learnt about the DOM, Loops, JavaScript Events and how to handle them, and we built a simple calculator at the end.
If you participate in the challenge in this post, please share your solution online and tag me @sprucekhalifa on Twitter. And don’t forget to follow me as well, as I tweet about JavaScript.
Пишем калькулятор на JavaScript
В этой статье мы с вами, как следует из названия, напишем простой калькулятор на JavaScript.
Желание написать калькулятор возникло у меня после просмотра одного туториала, посвященного созданию «simple calculator», который оказался далеко не симпл и толком ничего не умел делать.
Наш калькулятор будет true simple (42 строки кода, включая пробелы между блоками), но при этом полнофункциональным и масштабируемым.
Без дальнейших предисловий, приступаем к делу.
Наша разметка выглядит так:
Здесь мы подключаем библиотеку, создаем контейнер для калькулятора и поле для вводимых символов и результата.
Вот что мы имеем на данный момент:

Кнопки будут генерироваться программно.
Переходим к скрипту.
Определяем поле для вывода результата и создаем контейнер для клавиатуры:
Наша строка с символами выглядит так:
Преобразуем данную строку в массив и создаем кнопки:
Находим созданные кнопки и добавляем к ним обработчик события «клик»:
Мы также хотим иметь возможность вводить символы с помощью клавиатуры. Для этого нам необходимо добавить обработчик события «нажатие клавиши» к объекту «Document» или «Window», затем отфильтровать ненужные значения свойства «ключ» клавиши, например, с помощью регулярного выражения:
Метод «match» в данном случае играет роль фильтра: он не позволяет передавать функции «calc» аргумент, не соответствующий заданному в нем условию.
Само условие звучит так: если значением event.key является один из символов, указанных в квадратных скобках ([]; цифра от 0 до 9, знаки деления, умножения, сложения, вычитания, открывающая, закрывающая круглые скобки или знак равенства; обратная косая черта — экранирование) или (| — альтерация) Backspace, или Enter, то вызываем calc с event.key в качестве параметра, иначе ничего не делаем (Shift также успешно отбрасывается).
Наша главная (и единственная) функция «calc» выглядит следующим образом (код следует читать снизу вверх):
В завершение, парочка слов о заявленной масштабируемости и полнофункциональности.
Метод «evaluate» (ранее «eval») и другие методы Math.js имеют очень большие возможности. Опираясь на эти возможности, мы можем легко расширить функционал нашего калькулятора, добавив в него новые символы и операторы, предусмотрев возможность работы с числами с плавающей точкой (регулируя количество знаков после запятой с помощью переключателя и метода «toFixed») и т.д.
Благодарю за внимание. Надеюсь, вы нашли для себя что-то полезное. Хороших выходных и счастливого кодинга.