This is an easy project for beginners.
- Step 1: Create a basic HTML and CSS with a button and give a default background color.
<div id="background">
<h1>Changing Background Color</h1>
<button onclick="clickFunction()">Click Me</button>
</div>
- Step 2: Add a event listener or onclick function to button.
- Step 3: Create an Array of colors and once button is clicked the background will change. Use
Math.random()
to pick color randomly.
function clickFunction()
{
let bg = document.getElementById('background');
console.log(bg);
let colors = ["red", "green", "blue", "yellow"];
const colorIndex = parseInt(Math.random()*colors.length);
bg.style.backgroundColor = colors[colorIndex];
}
Top comments (0)