ws1v1
ws1v1
ws1v1
Objective
Create a basic calculator that can perform addition, subtraction, multiplication,
and division.
Instructions
1. Create three files: index.html , styles.css , and script.js .
Code to Type
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<div class="buttons">
<button class="btn" data-value="7">7</button>
<button class="btn" data-value="8">8</button>
<button class="btn" data-value="9">9</button>
<button class="btn" data-value="/">/</button>
<button class="btn" data-value="4">4</button>
<button class="btn" data-value="5">5</button>
<button class="btn" data-value="6">6</button>
styles.css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.calculator {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
#display {
width: 100%;
height: 40px;
font-size: 1.5em;
text-align: right;
.buttons {
display: grid;
grid-template-columns: repeat(4, 60px);
grid-gap: 10px;
}
.btn {
width: 60px;
height: 60px;
font-size: 1.2em;
border: none;
border-radius: 5px;
background-color: #e0e0e0;
cursor: pointer;
}
.btn:hover {
background-color: #d5d5d5;
}
#equals {
grid-column: span 2;
background-color: #4CAF50;
color: white;
}
#equals:hover {
background-color: #45a049;
}
#clear {
background-color: #f44336;
color: white;
}
script.js
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.getAttribute('data-value');
if (value) {
currentInput += value;
display.value = currentInput;
}
});
});
document.getElementById('equals').addEventListener('click',
() => {
try {
display.value = eval(currentInput);
currentInput = display.value;
} catch {
display.value = 'Error';
currentInput = '';
}
});
document.getElementById('clear').addEventListener('click',
() => {
currentInput = '';
display.value = '';
Key Points
Utilizes event listeners to handle button clicks.