JS Projects for Beginner – Change page background colour

Create a simple html page, Implement the JavaScript code such that every time the button is clicked on html page, the background colour of page should change.

Problem Statement credit: https://jsbeginners.com/javascript-projects-for-beginners/




Simple html page one button with ‘btn’ id



        <button id="btn">Hit Me!</button>

        <script type="text/javascript" src="./index.js"></script>



JS code:

In script, I have added event listener for button and on click inside function gets called,

Function creates a rgb colour value by calling the random function which generates number from 0 to 255.

document.getElementById("btn").addEventListener("click", function() {
    document.querySelector('body').style.backgroundColor =                             
'rgb('+ Math.floor(Math.random() * 256) + ','                                 
+ Math.floor(Math.random() * 256) 
+ ','                                 
+ Math.floor(Math.random() * 256)+ ')'  });

Git repository:


You can visit the live page


Leave a Reply

Your email address will not be published. Required fields are marked *