INTERNET CONCEPTS AND WEB DESIGN MCSL016
Write a program in JavaScript to create a simple calculator.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
.calculator {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
}
.button-row {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
.button {
width: calc(25% - 5px);
padding: 10px;
border: none;
border-radius: 5px;
background-color: #ccc;
cursor: pointer;
transition: background-color 0.3s;
}
.button:hover {
background-color: #999;
}
.display {
width: 100%;
padding: 10px;
margin-bottom: 10px;
box-sizing: border-box;
font-size: 18px;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" class="display" readonly>
<div class="button-row">
<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" onclick="appendToDisplay('+')">+</button>
</div>
<div class="button-row">
<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" onclick="appendToDisplay('-')">-</button>
</div>
<div class="button-row">
<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" onclick="appendToDisplay('*')">*</button>
</div>
<div class="button-row">
<button class="button" onclick="clearDisplay()">C</button>
<button class="button" onclick="appendToDisplay('0')">0</button>
<button class="button" onclick="calculate()">=</button>
<button class="button" onclick="appendToDisplay('/')">/</button>
</div>
</div>
<script>
function appendToDisplay(value) {
document.getElementById("display").value += value;
}
function clearDisplay() {
document.getElementById("display").value = "";
}
function calculate() {
var expression = document.getElementById("display").value;
var result = eval(expression);
document.getElementById("display").value = result;
}
</script>
</body>
</html>
No comments:
Post a Comment