Live Code Editor
Try it yourself..
Create simple calculator using HTML, CSS, and JavaScript
Create simple calculator using HTML, CSS, and JavaScript
HTML
xxxxxxxxxx
<div class="calculator">
<input type="text" id="display" disabled>
<div class="buttons">
<button class="button clear" onclick="clearDisplay()">C</button>
<button class="button delete" onclick="deleteLast()">DEL</button>
<button class="button operator" onclick="appendToDisplay('/')">/</button>
<button class="button operator" onclick="appendToDisplay('*')">*</button>
<button class="button" onclick="appendToDisplay('7')">7</button>
<button class="button" onclick="appendToDisplay('8')">8</button>
<button class="button" onclick="appendToDisplay('9')">9</button>
<button class="button operator" onclick="appendToDisplay('-')">-</button>
<button class="button" onclick="appendToDisplay('4')">4</button>
<button class="button" onclick="appendToDisplay('5')">5</button>
<button class="button" onclick="appendToDisplay('6')">6</button>
<button class="button operator" onclick="appendToDisplay('+')">+</button>
<button class="button" onclick="appendToDisplay('1')">1</button>
<button class="button" onclick="appendToDisplay('2')">2</button>
<button class="button" onclick="appendToDisplay('3')">3</button>
<button class="button equals" onclick="calculateResult()">=</button>
<button class="button zero" onclick="appendToDisplay('0')">0</button>
<button class="button" onclick="appendToDisplay('.')">.</button>
</div>
</div>
CSS
xxxxxxxxxx
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #282c34;
margin: 0;
font-family: 'Roboto', sans-serif;
color: #ffffff;
}
.calculator {
border: 1px solid #444;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
background-color: #1c1c1c;
}
#display {
width: 100%;
padding: 20px;
font-size: 2em;
border: none;
text-align: right;
background-color: #333;
color: #fff;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.button {
padding: 20px;
JavaScript
xxxxxxxxxx
function clearDisplay() {
document.getElementById('display').value = '';
}
function deleteLast() {
let display = document.getElementById('display');
display.value = display.value.slice(0, -1);
}
function appendToDisplay(value) {
let display = document.getElementById('display');
display.value += value;
}
function calculateResult() {
let display = document.getElementById('display');
try {
display.value = eval(display.value);
} catch (e) {
display.value = 'Error';
}
}