HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<div class="output">
<span id="result">0</span>
</div>
<div class="keys">
<button type="button" class="operator" value="clear">C</button>
<button type="button" value="backspace">CE</button>
<button type="button" class="operator" value="+">+</button>
<button type="button" value="7">7</button>
<button type="button" value="8">8</button>
<button type="button" value="9">9</button>
<button type="button" class="operator" value="-">-</button>
<button type="button" value="4">4</button>
<button type="button" value="5">5</button>
<button type="button" value="6">6</button>
<button type="button" class="operator" value="*">×</button>
<button type="button" value="1">1</button>
<button type="button" value="2">2</button>
<button type="button" value="3">3</button>
<button type="button" class="operator" value="/">÷</button>
<button type="button" value="0">0</button>
<button type="button" value=".">.</button>
<button type="button" class="eval" value="=">=</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: sans-serif;
background-color: #34495e;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calculator {
width: 400px;
background-color: #ecf0f1;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.output {
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: right;
margin-bottom: 20px;
}
.output span {
font-size: 36px;
}
.keys {
display: flex;
flex-wrap: wrap;
}
.keys button {
width: 75px;
height: 60px;
font-size: 24px;
border-radius: 10px;
margin: 10px;
background-color: white;
color: #34495e;
border: none;
outline: none;
cursor: pointer;
}
.keys button:active {
background-color: #c0392b;
color: white;
}
.operator {
background-color: #c0392b;
color: white;
}
.eval {
background-color: #2ecc71;
color: white;
}
java Script:
const buttons = document.querySelectorAll('button');
const result = document.querySelector('#result');
buttons.forEach(button => {
button.addEventListener('click', e => {
const value = e.target.value;
switch (value) {
case 'clear':
result.textContent = 0;
break;
case 'backspace':
result.textContent = result.textContent.slice(0, -1);
break;
case '=':
try {
result.textContent = eval(result.textContent);
} catch (e) {
result.textContent = 'Error';
}
break;
default:
result.textContent += value;
break;
}
});
});
Comments
Post a Comment