Greetings, fellow code artisans! Today, we embark on an enchanting journey to conjure a digital oracle — an elementary calculator that dances with numbers and performs the sacred arts of addition, subtraction, multiplication, and division. Join me as we wield HTML for the canvas and JavaScript for the mystical calculations, revealing the wizardry within our code.
Chapter 1: A Blank Canvas in HTML
Our journey commences with the humble HTML, the structure that lays the foundation for our magical calculator.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Magical Calculator</title>
<link rel="stylesheet" href="styles.css"> <!-- Link to our style sheet -->
</head>
<body>
<div class="calculator">
<!-- Display where the magic happens -->
<div class="display" id="display">0</div>
<!-- Buttons for digits and operations -->
<button id="clear">C</button>
<button id="btnBackspace">X</button>
<button class="operator">%</button>
<button class="operator">/</button>
<button class="digit">7</button>
<button class="digit">8</button>
<button class="digit">9</button>
<button class="operator">*</button>
<button class="digit">4</button>
<button class="digit">5</button>
<button class="digit">6</button>
<button class="operator">+</button>
<button class="digit">1</button>
<button class="digit">2</button>
<button class="digit">3</button>
<button class="operator">-</button>
<button class="digit">0</button>
<button class="digit">.</button>
<!-- The equals button to reveal the magic result -->
<button id="equals">=</button>
</div>
<!-- Our JavaScript spellbook -->
<script src="script.js"></script>
</body>
</html>
In this incantation, we have a div with the id “calculator” serving as our mystical realm. The display div showcases the numbers and results, while the buttons bear the numeric and operator symbols. Each button carries class
or id
attribute, linking to functions that shall weave the magic within.
Chapter 2: The Aesthetics — Styling with CSS
Before we delve into the magical calculations, let’s add a touch of style to our calculator. Open the styles.css file:
/* styles.css */
/* Apply Flexbox to Center the Calculator Vertically and Horizontally */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
background-color: #f0f0f0;
}
/* Calculator Styling */
.calculator {
width: 400px;
border: 2px solid #ccc;
border-radius: 10px;
overflow: hidden;
background-color: #000;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
color: #fff;
}
/* Display Area Styling */
.display {
width: calc(100% - 20px);
margin: 10px;
padding: 20px;
font-size: 30px;
border-bottom: 2px solid grey;
text-align: right;
box-sizing: border-box;
font-weight: bold;
}
/* Button Styling */
button {
width: 22%;
margin: 1%;
padding: 15px;
font-size: 1.5em;
font-weight: 500;
border: none;
border-radius: 10px;
outline: none;
cursor: pointer;
background-color: #000;
color: #fff;
transition: background-color 0.3s ease;
}
/* Button Hover Effect */
button:hover {
background-color: rgba(92, 92, 92, 0.2);
}
/* Operator Button Styling */
button.operator {
color: #ff9800;
}
/* Operator Button Hover Effect */
button.operator:hover {
background-color: rgba(92, 92, 92, 0.2);
}
/* Equals Button Styling */
button#equals {
width: 47%;
background-color: #FF7518;
}
/* Equals Button Hover Effect with Scale Animation */
button#equals:hover {
transform: scale(0.95);
}
/* Clear Button Styling */
button#clear {
color: #ff9800;
}
/* Clear Button Hover Effect */
button#clear:hover {
background-color: rgba(92, 92, 92, 0.2);
}
/* Backspace Button Styling */
button#btnBackspace {
color: #ff9800;
}
/* Backspace Button Hover Effect */
button#btnBackspace:hover {
background-color: rgba(92, 92, 92, 0.2);
}
This CSS spell adorns our calculator with elegance. The calculator div gets a gentle background, rounded corners, and a shadow, while the display and buttons receive a harmonious touch for visual appeal.
Chapter 3: The JavaScript Alchemy
Now, let’s breathe life into our calculator with JavaScript. Open the script.js file:
// script.js
// Our magical spellbook begins
// Initialize variables for calculator functionality
let displayValue = "0";
let firstOperand = null;
let operator = null;
// Function to update the display and dynamically adjust font size
function updateDisplay() {
const display = document.getElementById("display");
display.textContent = displayValue;
// Adjust font size based on the length of the displayed value
const maxLength = 20;
const fontSize = Math.min(30, 400 / Math.max(1, displayValue.length));
display.style.fontSize = `${fontSize}px`;
}
// Function to handle input of digits
function inputDigit(digit) {
// If the current display is '0', replace it with the new digit;
// otherwise, append the digit
displayValue = (displayValue === "0") ? digit : displayValue + digit;
updateDisplay();
}
// Function to handle input of operators
function inputOperator(op) {
// If an operator is already set, perform the operation
if (operator !== null) {
performOperation();
}
// Display the current input and operator
displayValue = `${displayValue} ${op} `;
// Store the first operand and operator for later calculation
operator = op;
firstOperand = parseFloat(displayValue);
updateDisplay();
}
// Function to handle backspace button
function handleBackspace() {
// Remove the last character from the display
displayValue = displayValue.slice(0, -1);
updateDisplay();
}
// Function to perform the selected operation
function performOperation() {
const secondOperand = parseFloat(displayValue.split(' ')[2]);
switch (operator) {
case "+":
displayValue = firstOperand + secondOperand;
break;
case "-":
displayValue = firstOperand - secondOperand;
break;
case "*":
displayValue = firstOperand * secondOperand;
break;
case "/":
displayValue = firstOperand / secondOperand;
break;
case "%":
displayValue = firstOperand % secondOperand;
break;
}
// Reset operator and store the result as the new first operand
operator = null;
firstOperand = parseFloat(displayValue);
displayValue = firstOperand.toString();
updateDisplay();
}
// Function to handle clear button
function clear() {
// Reset all variables and update the display
displayValue = "0";
firstOperand = null;
operator = null;
updateDisplay();
}
// Add event listeners to digit buttons, operator buttons, and clear button
document.querySelectorAll(".digit").forEach((button) => {
button.addEventListener("click", () => inputDigit(button.textContent));
});
document.querySelectorAll(".operator").forEach((button) => {
button.addEventListener("click", () => inputOperator(button.textContent));
});
document.getElementById("equals").addEventListener("click", performOperation);
document.getElementById("clear").addEventListener("click", clear);
// Add event listener for the backspace button
document.getElementById("btnBackspace").addEventListener("click", handleBackspace);
// Add event listener for the clear button (assuming it has an id of "btnClear")
document.getElementById("btnClear").addEventListener("click", handleClearClick);
This JavaScript spellbook orchestrates the dance of digits and operators. Let’s unravel the magic:
1. Initialization:
Variables are declared to manage the calculator’s state.
displayValue
: Represents the current value displayed on the calculator.firstOperand
: Stores the first operand for arithmetic operations.operator
: Keeps track of the selected arithmetic operator.
2. updateDisplay() Function:
Responsible for updating the calculator display and adjusting font size dynamically.
Retrieves the display element from the HTML.
Sets the text content of the display to the current
displayValue
.Calculates the appropriate font size based on the length of the displayed value.
Updates the font size of the display element accordingly.
3. inputDigit() Function:
Handles the input of digits when a digit button is clicked.
Checks if the current display is ‘0’; if so, replaces it with the new digit; otherwise, appends the digit to the existing value.
Calls the
updateDisplay
function to reflect the changes on the display.
4. inputOperator() Function:
Manages the input of operators when an operator button is clicked.
If an operator is already set, it performs the operation using the
performOperation
function.Displays the current input and operator on the calculator.
Stores the first operand and the selected operator for later calculation.
Calls the
updateDisplay
function to reflect the changes on the display.
5. handleBackspace() Function:
Handles the backspace button to remove the last character from the display.
Uses the
slice
method to remove the last character from thedisplayValue
.Calls the
updateDisplay
function to reflect the changes on the display.
6. performOperation() Function:
Performs the selected arithmetic operation when the equals button is clicked.
Retrieves the second operand from the displayed expression.
Switches based on the stored operator and performs the corresponding operation.
Resets the operator and stores the result as the new first operand.
Converts the result to a string and updates the display.
7. clear() Function:
Resets the calculator state when the clear button is clicked.
Sets
displayValue
to “0”, andfirstOperand
andoperator
to null.Calls the
updateDisplay
function to reflect the changes on the display.
8. Event Listeners:
Adds event listeners to various buttons in the HTML, connecting them to the corresponding functions.
Digit buttons trigger the
inputDigit
function.Operator buttons trigger the
inputOperator
function.The equals button triggers the
performOperation
function.The clear button triggers the
clear
function.The backspace button triggers the
handleBackspace
function.
These functions collectively create a functional and visually appealing calculator that handles user input, performs arithmetic operations, and provides a responsive and dynamic display.
JavaScript Concepts Unveiled
In this captivating journey, we’ve touched upon fundamental JavaScript concepts that form the backbone of countless web applications:
Variables and Data Types: From storing the display value to keeping track of operands and operators, variables play a pivotal role in managing data.
Functions: The building blocks of our calculator, functions encapsulate logic and promote code organization, fostering modularity and reusability.
Event Listeners: Enabling our calculator to respond to user input, event listeners showcase JavaScript’s ability to capture and handle actions in real-time.
DOM Manipulation: Updating the Document Object Model dynamically with each interaction demonstrates JavaScript’s prowess in altering the structure and content of a web page.
Conditional Statements: Guiding the flow of our calculator’s logic, conditional statements ensure that the correct operations are executed based on user input.
The Grand Finale
Open your enchanted HTML page in a browser. Click the numeric and operator buttons, witness the display updating, and finally, marvel at the result when you press equals. Our simple calculator, crafted with HTML and animated by JavaScript, is now ready to unveil the magic of arithmetic.
CLICK HERE to check the final Output.
Epilogue: The Infinite Possibilities
As you traverse the realms of web development, remember that each line of code is a spell, capable of conjuring unique digital experiences. Our humble calculator, a fusion of HTML and JavaScript, is a testament to the infinite possibilities that code offers.
May you continue to explore, experiment, and weave your own magic in the wondrous world of web development. Happy coding, and may your calculators always calculate correctly!
Top comments (0)