In this blog post, we'll walk through the creation of a simple calculator using HTML, CSS, and JavaScript. We'll explore the various scenarios in which this calculator can be handy and include the complete code for you to try out.
Introduction
A calculator is a fundamental tool that we use almost daily for simple arithmetic operations. Building a web-based calculator not only aids in quick calculations but also serves as an excellent exercise for learning web development.
Use Cases
Here are a few scenarios where this calculator can be useful:
- Educational Purposes: This calculator can be an effective teaching tool to help students understand basic arithmetic operations and coding concepts.
- Quick Calculations: Need to do some quick math? This calculator can be accessed from any browser without needing a separate application.
- Web Development Learning: Creating this calculator is a great exercise to grasp HTML, CSS, and JavaScript basics.
- Integration into Websites: If you own a finance-related or similar website, integrating this calculator can provide additional functionality for your users.
- Personal Projects: This project can be a fun personal tool that you can customize and expand as needed.
Step-by-Step Guide
Here's how you can create your own simple calculator:
HTML Code
This is the structure of our calculator, including a display area and buttons for each number and operation:
<!DOCTYPE html> <html> <head> <title>Simple Calculator</title> <style> .calculator { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; width: 250px; margin: auto; padding: 20px; border: 2px solid #ccc; border-radius: 10px; } .calculator input, .calculator button { width: 100%; padding: 10px; font-size: 18px; } #display { grid-column: span 5; text-align: right; margin-bottom: 10px; padding-right: 10px; } </style> </head> <body> <h1 style="text-align: center;">Simple Calculator</h1> <div class="calculator"> <input type="text" id="display" disabled> <button onclick="appendNumber(7)">7</button> <button onclick="appendNumber(8)">8</button> <button onclick="appendNumber(9)">9</button> <button onclick="setOperation('+')">+</button> <button onclick="clearDisplay()">C</button> <button onclick="appendNumber(4)">4</button> <button onclick="appendNumber(5)">5</button> <button onclick="appendNumber(6)">6</button> <button onclick="setOperation('-')">−</button> <button onclick="cancelLastEntry()">CE</button> <button onclick="appendNumber(1)">1</button> <button onclick="appendNumber(2)">2</button> <button onclick="appendNumber(3)">3</button> <button onclick="setOperation('×')">×</button> <button onclick="calculateSquareRoot()">√</button> <button onclick="appendNumber(0)">0</button> <button onclick="calculate()">=</button> <button onclick="clearDisplay()">C</button> <button onclick="setOperation('÷')">÷</button> </div> <script src="calculator.js"></script> </body> </html>
JavaScript Code
Here is the logic behind the calculator, which handles the operations and updates the display:
let currentNumber = ''; let previousNumber = ''; let operation = ''; let sqrtPending = false; function appendNumber(number) { currentNumber += number; updateDisplay(); } function setOperation(op) { if (currentNumber === '' && op !== '√') return; operation = op; if (op === '√') { sqrtPending = true; } else { previousNumber = currentNumber; currentNumber = ''; } updateDisplay(); } function calculate() { let result; const num1 = parseFloat(previousNumber); const num2 = parseFloat(currentNumber); switch(operation) { case '+': result = num1 + num2; break; case '−': result = num1 - num2; break; case '×': result = num1 * num2; break; case '÷': result = num1 / num2; break; case '√': result = Math.sqrt(num2); break; default: result = 'Invalid operation'; } document.getElementById('display').value = `${previousNumber} ${operation} ${currentNumber} = ${result}`; previousNumber = ''; currentNumber = result.toString(); operation = ''; sqrtPending = false; } function clearDisplay() { currentNumber = ''; previousNumber = ''; operation = ''; sqrtPending = false; updateDisplay(); } function cancelLastEntry() { currentNumber = currentNumber.slice(0, -1); updateDisplay(); } function updateDisplay() { if (sqrtPending) { document.getElementById('display').value = `√ ${currentNumber}`; } else { document.getElementById('display').value = `${previousNumber} ${operation} ${currentNumber}`; } }
Explanation of JavaScript Functions
Here's a detailed explanation of each function used in the JavaScript code:
appendNumber(number)
: This function appends the given number to the current input and updates the display accordingly.setOperation(op)
: This function sets the chosen operation (addition, subtraction, multiplication, division, or square root). If the operation is square root, it setssqrtPending
totrue
. Otherwise, it stores the current input as the previous number and clears the current input.calculate()
: This function performs the calculation based on the selected operation. It converts the input numbers to floating-point numbers and uses a switch statement to perform the appropriate operation. The result is then displayed.clearDisplay()
: This function clears the display and resets all variables to their initial state.cancelLastEntry()
: This function removes the last digit from the current input and updates the display.updateDisplay()
: This function updates the display to show the current state of the calculator, including the previous number, the selected operation, and the current input. If the square root operation is pending, it will show the square root symbol followed by the current input.
Live Demo (Preview)
Conclusion
Building this simple calculator allows you to perform quick calculations, integrates well with educational settings, and serves as a fantastic learning project for budding web developers. Feel free to customize and expand its functionalities according to your needs!
Happy coding! 😊
Leave a Reply