Create webpage with button that changes color
Wed Feb 28 2024 00:55:39 GMT+0000 (Coordinated Universal Time)
Saved by
@Sliderk21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Color Changer</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Background Color Changer</h1>
<button id="changeColorBtn">Change Color</button>
<script>
// Selecting the button element
const changeColorBtn = document.getElementById('changeColorBtn');
// Adding an event listener to the button
changeColorBtn.addEventListener('click', function() {
// Generating a random color
const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
// Changing the background color of the body
document.body.style.backgroundColor = randomColor;
// Logging the color change
console.log('Background color changed to: ' + randomColor);
});
</script>
</body>
</html>
content_copyCOPY
In this example:
- We use HTML to create the structure of the webpage, including a button with the id 'changeColorBtn'.
- We use CSS to style the elements on the page.
- In the JavaScript section:
- - We select the button element using 'getElementById'.
- - We add an event listener to the button using 'addEventListener', which listens for a 'click' event and executes a callback function when the button is clicked.
- - Inside the callback function, we generate a random color using 'Math.random()' and set it as the background color of the body element using 'document.body.style.backgroundColor'.
- - We also log the color change to the console using 'console.log'.
This example demonstrates fundamental concepts such as DOM manipulation, event handling, and basic JavaScript syntax.
Comments