Creating an HTML page that demonstrates event handling, selectors, and dynamic styling using CSS is a great way to learn how to manipulate the DOM. Here's a detailed example of such a page:
This HTML page creates a simple calculator with two input fields for numbers, a select dropdown for selecting the operation, and a button to perform the calculation.
When you click the "Calculate" button, the result is displayed, and the button's color changes randomly. You can further customize the styles and functionality as needed.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
text-align: center;
margin-top: 100px;
} input[type="number"] {
padding: 10px;
margin: 10px;
width: 80px;
} select, button {
padding: 10px;
} #result {
font-size: 24px;
margin-top: 20px;
} /* CSS for changing colors on button click */
.change-color {
background-color: #3498db;
color: white;
} .change-color:hover {
background-color: #2c3e50;
}
</style>
</head>
<body>
<div class="container">
<h2>Simple Calculator</h2>
<input type="number" id="num1" placeholder="Enter a number">
<select id="operator">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="number" id="num2" placeholder="Enter another number">
<button id="calculate" class="change-color">Calculate</button>
<p id="result"></p>
</div> <script>
// Function to perform the calculation and update the result field
function performCalculation() {
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operator = document.getElementById('operator').value;
let result; switch (operator) {
case 'add':
result = num1 + num2;
break;
case 'subtract':
result = num1 - num2;
break;
case 'multiply':
result = num1 * num2;
break;
case 'divide':
if (num2 !== 0) {
result = num1 / num2;
} else {
result = 'Division by zero is undefined';
}
break;
} const resultField = document.getElementById('result');
resultField.textContent = `Result: ${result}`;
} // Event listener for the Calculate button click
const calculateButton = document.getElementById('calculate');
calculateButton.addEventListener('click', performCalculation); // Event listener to change colors on button click
calculateButton.addEventListener('click', () => {
const colors = ['#e74c3c', '#27ae60', '#f1c40f', '#3498db'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
calculateButton.style.backgroundColor = randomColor;
});
</script>
</body>
</html>