DEV Community

loading...

Changing Background Color in JS(project for beginners)

umapreethidev profile image Umapreethi Santhanakrishnan ・1 min read

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>
Enter fullscreen mode Exit fullscreen mode
  • 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];
 }
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide