Simple Calculator Web App JavaScript Coding Exercise
Download JavaScript PDF guide https://basescripts.com/simple-calculator-web-app-javascript-coding-exercise
Exercise 1: Simple Calculator
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
??<meta charset="UTF-8">
??<meta name="viewport" content="width=device-width, initial-scale=1.0">
??<link rel="stylesheet" href="styles.css">
??<title>Simple Calculator</title>
</head>
<body>
??<div class="calculator">
????<input type="text" id="display" readonly>
????<div class="buttons">
??????<button onclick="clearDisplay()">C</button>
??????<button onclick="appendToDisplay('1')">1</button>
??????<button onclick="appendToDisplay('2')">2</button>
??????<button onclick="appendToDisplay('+')">+</button>
??????<!-- Add more buttons as needed -->
??????<button onclick="calculate()">=</button>
????</div>
??</div>
??<script src="script.js"></script>
</body>
</html>
CSS (styles.css):
body {
??display: flex;
??justify-content: center;
??align-items: center;
??height: 100vh;
??margin: 0;
}
.calculator {
??text-align: center;
}
input {
领英推荐
??width: 200px;
??padding: 10px;
??font-size: 18px;
}
button {
??width: 50px;
??height: 50px;
??font-size: 18px;
??margin: 5px;
}
JavaScript (script.js):
let displayValue = '';
function appendToDisplay(value) {
??displayValue += value;
??document.getElementById('display').value = displayValue;
}
function clearDisplay() {
??displayValue = '';
??document.getElementById('display').value = displayValue;
}
function calculate() {
??try {
????displayValue = eval(displayValue);
????document.getElementById('display').value = displayValue;
??} catch (error) {
????document.getElementById('display').value = 'Error';
??}
}
function appendToDisplay(value) { ... }
function clearDisplay() { ... }
function calculate() { ... }
In summary, these functions together form the core functionality of a simple calculator, allowing users to input values, perform calculations, and handle errors gracefully. The displayValue variable acts as a buffer for the input and results, and the functions manipulate it based on user interactions.