Generating Random Colors
Method 1: RGB mode using array mapping
function createRandomRGB() {
// Generate three independent random values between 0 and 255
const components = [0, 0, 0].map(() => Math.floor(Math.random() * 256));
const color = `rgb(${components[0]}, ${components[1]}, ${components[2]})`;
console.log(color);
return color;
}
Method 2: Random 6‑character hex string (full heaxdecimal range)
function generateRandomHex() {
const hexDigits = '0123456789ABCDEF';
let code = '#';
for (let i = 0; i < 6; i++) {
code += hexDigits.charAt(Math.floor(Math.random() * 16));
}
console.log(code);
return code;
}
Automatically Cycling the Page Background Color
This implementation uses setInterval to apply a new color every 300 milliseconds. Toggling the timer is managed through button state.
let intervalId = null;
function beginCycle() {
// Start the interval and apply new colors repeatedly
intervalId = setInterval(() => {
document.body.style.backgroundColor = createRandomRGB();
}, 300);
// Update button availability
document.getElementById('btnStop').disabled = false;
document.getElementById('btnStart').disabled = true;
}
function endCycle() {
clearInterval(intervalId);
document.getElementById('btnStop').disabled = true;
document.getElementById('btnStart').disabled = false;
}
Complete Working Example
The following HTML documetn includes all the functions and controls for manual color changes and automatic cycling.
<html>
<head>
<meta charset="UTF-8">
<title>Random Background Color Switcher</title>
</head>
<body>
<button id="btnRgb" onclick="applyColor(createRandomRGB())">Set Background (RGB)</button>
<button id="btnHex" onclick="applyColor(generateRandomHex())">Set Background (Hex)</button>
<br>
<button id="btnStart" onclick="beginCycle()">Start Auto Cycle</button>
<button id="btnStop" onclick="endCycle()" disabled>Stop Auto Cycle</button>
<script>
function applyColor(color) {
document.body.style.backgroundColor = color;
}
function createRandomRGB() {
const components = [0, 0, 0].map(() => Math.floor(Math.random() * 256));
const color = `rgb(${components[0]}, ${components[1]}, ${components[2]})`;
console.log(color);
return color;
}
function generateRandomHex() {
const hexDigits = '0123456789ABCDEF';
let code = '#';
for (let i = 0; i < 6; i++) {
code += hexDigits.charAt(Math.floor(Math.random() * 16));
}
console.log(code);
return code;
}
let intervalId = null;
function beginCycle() {
intervalId = setInterval(() => {
document.body.style.backgroundColor = createRandomRGB();
}, 300);
document.getElementById('btnStop').disabled = false;
document.getElementById('btnStart').disabled = true;
}
function endCycle() {
clearInterval(intervalId);
document.getElementById('btnStop').disabled = true;
document.getElementById('btnStart').disabled = false;
}
// Optional: start cycling automatically when the page loads
window.addEventListener('load', beginCycle);
</script>
</body>
</html>