Калькулятор

Пишем калькулятор на JavaScript

В этой статье мы с вами, как следует из названия, напишем простой калькулятор на JavaScript.

Желание написать калькулятор возникло у меня после просмотра одного туториала, посвященного созданию «simple calculator», который оказался далеко не симпл и толком ничего не умел делать.

Наш калькулятор будет true simple (42 строки кода, включая пробелы между блоками), но при этом полнофункциональным и масштабируемым.

Без дальнейших предисловий, приступаем к делу.

Наша разметка выглядит так:

Здесь мы подключаем библиотеку, создаем контейнер для калькулятора и поле для вводимых символов и результата.

* < margin: 0; padding: 0; box-sizing: border-box; >body < height: 100vh; background: radial-gradient(circle, skyblue, steelblue); display: flex; justify-content: center; align-items: center; >.calculator < width: 320px; height: 480px; background: #eee; border-radius: 5px; box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2), -2px -2px 3px rgba(0, 0, 0, 0.2); >output < display: flex; justify-content: center; align-items: center; width: 300px; height: 40px; background: #fff; margin: 10px auto; border-radius: 5px; font-size: 1.4em; font-weight: bold; box-shadow: inset 1px 1px 1px rgba(0, 0, 0, 0.3), inset -1px -1px 1px rgba(0, 0, 0, 0.3); >.keyboard < height: 440px; display: flex; flex-wrap: wrap; justify-content: space-evenly; align-items: flex-start; >button

Вот что мы имеем на данный момент:

Кнопки будут генерироваться программно.

Определяем поле для вывода результата и создаем контейнер для клавиатуры:

const output = document.querySelector('output') const div = document.createElement('div') div.classList.add('keyboard') document.querySelector('.calculator').appendChild(div) 

Наша строка с символами выглядит так:

'C CE % / 7 8 9 * 4 5 6 - 1 2 3 + 0 ( ) =' 

Преобразуем данную строку в массив и создаем кнопки:

// разделителем служит пустая строка // можно было бы обойтись без пробелов, если бы у нас не было "CE" 'C CE % / 7 8 9 * 4 5 6 - 1 2 3 + 0 ( ) ='.split(' ') // пробегаемся по массиву // для каждого символа // создаем кнопку с помощью строкового литерала // записываем значение символа в атрибут "value" кнопки .map(symbol => < div.insertAdjacentHTML('beforeend', `">$ `) >) 

Находим созданные кнопки и добавляем к ним обработчик события «клик»:

document.querySelectorAll('button').forEach(button => < button.addEventListener('click', function () < // по клику вызывается функция со значением кнопки в качестве параметра calc(this.value) >) >) 

Мы также хотим иметь возможность вводить символы с помощью клавиатуры. Для этого нам необходимо добавить обработчик события «нажатие клавиши» к объекту «Document» или «Window», затем отфильтровать ненужные значения свойства «ключ» клавиши, например, с помощью регулярного выражения:

document.addEventListener('keydown', event => < if ((event.key).match(/[0-9%\/*\-+\(\)=]|Backspace|Enter/)) calc(event.key) >) 

Метод «match» в данном случае играет роль фильтра: он не позволяет передавать функции «calc» аргумент, не соответствующий заданному в нем условию.

Само условие звучит так: если значением event.key является один из символов, указанных в квадратных скобках ([]; цифра от 0 до 9, знаки деления, умножения, сложения, вычитания, открывающая, закрывающая круглые скобки или знак равенства; обратная косая черта — экранирование) или (| — альтерация) Backspace, или Enter, то вызываем calc с event.key в качестве параметра, иначе ничего не делаем (Shift также успешно отбрасывается).

Наша главная (и единственная) функция «calc» выглядит следующим образом (код следует читать снизу вверх):

// функция принимает значение кнопки или ключ клавиши function calc(value) < // если нажат знак равенства или Enter if (value.match(/=|Enter/)) < // пробуем выполнить операцию try < // вычисляем значение строки // это возможно благодаря методу "evaluate" объекта "math" // Math.trunc используется для округления до целого числа output.textContent = Math.trunc(math.evaluate(output.textContent)) // если операцию выполнить невозможно >catch < // сохраняем значение поля let oldValue = output.textContent // создаем новую переменную let newValue = 'недопустимое выражение' // выводим значение новой переменной в поле output.textContent = newValue // через полторы секунды возвращаем полю старое значение setTimeout(() =>< output.textContent = oldValue >, 1500) > // если нажат символ "C" > else if (value === 'C') < // очищаем поле output.textContent = '' // если нажат символ "СЕ" или Backspace >else if (value.match(/CE|Backspace/)) < // уменьшаем строку на один символ output.textContent = output.textContent.substring(0, output.textContent.length - 1) // если нажата любая другая (отфильтрованная) кнопка или клавиша >else < // записываем ее значение в поле output.textContent += value >> 

В завершение, парочка слов о заявленной масштабируемости и полнофункциональности.

Читайте также:  Bot send message python telebot

Метод «evaluate» (ранее «eval») и другие методы Math.js имеют очень большие возможности. Опираясь на эти возможности, мы можем легко расширить функционал нашего калькулятора, добавив в него новые символы и операторы, предусмотрев возможность работы с числами с плавающей точкой (регулируя количество знаков после запятой с помощью переключателя и метода «toFixed») и т.д.

Благодарю за внимание. Надеюсь, вы нашли для себя что-то полезное. Хороших выходных и счастливого кодинга.

Источник

Простой калькулятор на JavaScript

Сегодня сделаем простейший калькулятор на JavaScript, но не просто так, а с умыслом. Позднее мы представим, что мы тестировщики, и попробуем протестировать этот калькулятор. Вернее, не протестировать, а дико сломать.

Что делаем

На старте у нас будет самый простой калькулятор, который сможет только складывать, вычитать, умножать и делить два числа. Этого уже будет достаточно, чтобы потренироваться и в коде, и в дальнейшем тестировании.

Логика работы

Так как это простой калькулятор, то поступим так:

  1. Сделаем поле ввода для первого числа.
  2. Под ним разместим 4 кнопки с математическими действиями.
  3. Потом сделаем поле ввода для второго числа.
  4. И внизу будет кнопка «Посчитать».

Размещаем кнопки и поля ввода на странице

Разместим кнопки с полями на странице, а потом будем писать скрипт.

         
+

Простой калькулятор на JavaScript

Обрабатываем нажатия на кнопки математических действий

Сейчас у нас есть 4 кнопки, но нажимать их бесполезно — всё равно ничего не произойдёт, потому что нет обработчиков нажатий. Но что нам прописывать в обработчике?

Первый вариант — привязать к каждой кнопке свою функцию, а потом для каждой операции выполнять свои действия внутри этого обработчика. Но раз у нас есть кнопка «Посчитать», то нам придётся при нажатии на неё из этих четырёх функций вытаскивать действие и нужные команды, запоминать выбранное и как-то использовать в вычислениях. Сложно и громоздко.

Второй вариант — просто записывать в какую-то переменную, какая кнопка была нажата. А потом, при нажатии «Посчитать», просто смотреть в эту переменную и выполнять соответствующее действие. Так и поступим.

👉 Воспользуемся хитростью, про которые многие забывают: в обработчике onclick необязательно писать только функцию — туда можно отправить любую JS-команду. Главное, не забыть потом в скрипте предусмотреть эту переменную, которую мы используем.

Источник

Create a simple calculator using HTML, CSS and Javascript

In this tutorial we will create a fully working calculator using only HTML, CSS and vanilla Javascript. You’ll learn about event handling, and DOM manipulations throughout the project. In my opinion this is a really good beginner project for those who want to become web developers.

Video Tutorial

If you would watch a detailed step-by-step video instead you can check out the video I made covering this project on my Youtube Channel:

HTML

The html will be pretty simple for this project. We’ll start out with a standard HTML5 boilerplate. At the bottom of our body I included the index.js script that we will create later. This needs to be at the bottom, because this way, when our javascript runs, the html elements required for the calculator will be in the DOM.
In the body we have a section and inside that a div with a container class. We will use these wrappers to position our calculator on the page. Inside our container we have an empty div with the id of display , and this will be the display of our calculator. It is empty, because we will modify its content from Javascript. Then we have a div with the class of buttons which will represent the keypad of the calculator.

   class="container">  id="display">
class="buttons"> src="index.js">

The buttons container will hold all of the buttons. Each button will be a div with a class of button . This will make the styling easy, and also will help us to gather the user input. Here we have a div for every button that we want on our keypad. You can notice that we have a weird looking label between the buttons: ← . This is a HTML entity and it renders a back arrow (←), and we’ll use this as a backspace. Also please not that for the equal sign button we have a separate id equal . We will use this Id to distinguish this special button, and evaluate the expression provided to the calculator.

  class="buttons">  class="button">C  class="button">/  class="button">*  class="button">   class="button">7  class="button">8  class="button">9  class="button">-  class="button">4  class="button">5  class="button">6  class="button">+  class="button">1  class="button">2  class="button">3  class="button">.  class="button">(  class="button">0  class="button">)  id="equal" class="button">=  

And this is all of the HTML markup that we need for this project, let’s jump into CSS. Don’t forget to link the CSS styleshead in the head of the HTML file:

 rel="stylesheet" href="style.css"> 

CSS

Let’s create a style.css file.
We set a width for the container and center it using margin (also give it a decent top margin of 10vh), and apply a little box shadow.

.container  max-width: 400px; margin: 10vh auto 0 auto; box-shadow: 0px 0px 43px 17px rgba(153,153,153,1); > 

For the display we set a fixed height, and to center the text vertically we need to set the line-height to the exact same amount. The text should be right align, because this is how most calculator displays work. Also set the font-size and give a decent amount paddings.

#display  text-align: right; height: 70px; line-height: 70px; padding: 16px 8px; font-size: 25px; > 

To position the buttons we use CSS grid. By setting 4 x 1fr in- grid-template-coloumns we’ll have 4 equally sized buttons in each row. We only set bottom and left borders, so we won’t get double borders. We’ll set the other two sides in the next CSS rule.

.buttons  display: grid; border-bottom: 1px solid #999; border-left: 1px solid#999; grid-template-columns: 1fr 1fr 1fr 1fr; > 
.buttons > div  border-top: 1px solid #999; border-right: 1px solid#999; > 

For the button we’ll set borders, font-size and 100px of line height to center it vertically, and set text-align: center to center the button labels horizontally. To have a better user experience set cursor to pointer, so the user will know that this is a clickable element.

.button  border: 0.5px solid #999; line-height: 100px; text-align: center; font-size: 25px; cursor: pointer; > 

We want the equal button to stand out so, we’ll set a blue background color and white text to it. Also to have a nice hover effect we’ll set a darker background color and white text color on hover. To make the transition smoot set: transition: 0.5s ease-in-out; .

#equal  background-color: rgb(85, 85, 255); color: white; > .button:hover  background-color: #323330; color: white; transition: 0.5s ease-in-out; > 

Javascript

This will be the heart of our application. Let’s create the index.js file. The first thing we need to do is to save a reference to our display dom element. We can easily do that because it has an id of display .

let display = document.getElementById('display'); 

Next we have to get references for the buttons. We’ll store the button references in an array. To gather the buttons we can select them by document.getElementsByClassName(‘button’) , but this function gives back a NodeCollection instead of an array so we have to convert it to an array using Array.from() .

let buttons = Array.from(document.getElementsByClassName('button')); 

The next and last step we have to make is to add event listener to the buttons and build the functionalities. To add event listeners for the buttons, we’ll map through the buttons array and add a click event listener for each. (An advanced solution would be to only add event listener to the buttons container and use event bubbling but this is a more beginner-friendly solution.) To determine what should we do, we’ll use e.target.innerText , which will simply give back the label of the button that was clicked. In the first case, when the user hits the «C» button we’d like to clear the display. To do that we can access our display reference and set the innerText to an empty string. Don’t forget to add break; at the end, because it is needed to prevent the execution of the code defined in other case blocks. For the equal button we’ll use javascript built in eval function. We need to provide the display’s content to eval and it will evaluate and return the result, so we should set the result of the eval call to the display’s innerText. We need to wrap this into a try catch block to handle errors. Erros can happen when we have syntactically wrong math expressions, for example //(9( , ine these cases we’ll set the display’s innerText to display ‘Error’. ⚠️ You should not use eval in user facing applications, because it can be abused and external code can be run with it. More details If you want to replace eval I suggest using Math.js lib. If the user hits the back arrow we need to remove the last character from the display’s innerText. To do that we’ll use the String.slice() method, but we only want to do that if the display has any value. In the default case, so whenever the user don’t hit these special symbols we just want to append the clicked button’s innerText to the display’s innerText. We can use the += operator to do that.

buttons.map( button =>  button.addEventListener('click', (e) =>  switch(e.target.innerText) case 'C': display.innerText = ''; break; case '=': try display.innerText = eval(display.innerText); > catch  display.innerText = "Error" > break; case '': if (display.innerText) display.innerText = display.innerText.slice(0, -1); > break; default: display.innerText += e.target.innerText; > >); >); 

The whole project is available on GitHub
And that’s it you have a working calculator. Thanks for reading.

Where you can learn more from me?

  • 🍺 Support free education and buy me a beer
  • 💬 Join our community on Discord
  • 📧 Newsletter Subscribe here
  • 🎥 YouTube Javascript Academy
  • 🐦 Twitter: @dev_adamnagy
  • 📷 Instagram @javascriptacademy

Источник

Оцените статью