Table of contents
In this project, we will create a simple web page where the background color changes every second when the "Start" button is pressed and stops changing when the "Stop" button is pressed. Let's dive into the HTML, CSS, and JavaScript code that makes this possible.
HTML
The HTML structure is straightforward. It includes two buttons to start and stop the background color change and a title to guide the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Background Color Changer</title>
<link rel="stylesheet" href="style.css" />
</head>
<body style="background-color: #212121; color: #fff">
<h1>Start should change the Background color every second</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script src="script.js"></script>
</body>
</html>
CSS
We can use some simple CSS to style our page, but for this example, the focus is on the functionality, so there's minimal CSS.
JavaScript
The JavaScript code handles the main functionality of changing the background color. Let's break down the code:
// Generate a random color
const randomColor = function () {
const hex = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += hex[Math.floor(Math.random() * 16)];
}
return color;
};
let intervalId;
// Function to start changing the background color
const startChangingColor = function () {
function changeBgColor() {
document.body.style.backgroundColor = randomColor();
}
if (!intervalId) {
intervalId = setInterval(changeBgColor, 1000);
}
// Alternative way to write the if condition:
// if(intervalId == null){
// intervalId = setInterval(changeBgColor, 1000);
// }
};
// Function to stop changing the background color
const stopChangingColor = function () {
clearInterval(intervalId);
intervalId = null;
};
document.querySelector('#start').addEventListener('click', startChangingColor);
document.querySelector('#stop').addEventListener('click', stopChangingColor);
Explanation
- Generating a Random Color:
The randomColor
function generates a random hex color code. It does this by selecting random characters from a string of hex digits and concatenating them to form a valid hex color code.
const randomColor = function () {
const hex = '0123456789ABCDEF'; // hexadecimal ranges are 0-9 and A-F
let color = '#';
for (let i = 0; i < 6; i++) { //A hex color code is a 6‑symbol code
color += hex[Math.floor(Math.random() * 16)];
}
return color;
};
- Starting the Color Change:
The startChangingColor
function uses setInterval
to repeatedly call the changeBgColor
function every second (1000 milliseconds). It ensures that only one interval is running at a time by checking if intervalId
is null
or not set.
const startChangingColor = function () {
function changeBgColor() {
document.body.style.backgroundColor = randomColor();
}
if (!intervalId) {
intervalId = setInterval(changeBgColor, 1000);
}
// Alternative way to write the if condition:
// if(intervalId == null){
// intervalId = setInterval(changeBgColor, 1000);
// }
};
- Stopping the Color Change:
The stopChangingColor
the function stops the interval using clearInterval
and resets intervalId
to null
.
const stopChangingColor = function () {
clearInterval(intervalId);
intervalId = null;
};
- Event Listeners:
The event listeners for the "Start" and "Stop" buttons trigger the respective functions when clicked.
document.querySelector('#start').addEventListener('click', startChangingColor);
document.querySelector('#stop').addEventListener('click', stopChangingColor);
Wrap Up
With this simple project, we've demonstrated how to use JavaScript to manipulate the DOM and create interactive web pages. The key concepts include generating random colors, using setInterval
to create repetitive tasks, and managing those tasks with event listeners and clearInterval
. This foundation can be expanded to create more complex and dynamic web applications.