Background color change – Javascript Beginner [01]





Hey guys, welcome to the javascript beginner project series. In this post, we will create a javascript project which changes the background color of the webpage on click of the button. This project is for absolute beginners, we will learn about javascript Math.random() to generate random numbers between 2 numbers. So let’s begin.

Check the live version of the project here

Development Process


First, we will set up our project by creating an empty folder

Setup the project


Create a folder on your desktop with the name change-bg-color

Next, navigate to the newly created folder

Create 3 files, index.html, app.js, style.css inside the change-bg-color



Design the HTML template


open index.html and add the following contents

Inside the <head> tag we are linking to the style sheet style.css and just before closing the </body> tag, we are linking to the script file app.js. Inside the <body> tag we have only one button with id changecolor.

Apply a style to HTML content


Next, open style.css and add the following content

Adding logic to change background-color


Next, open app.js file and add the following logic to change the background color.

Here we are creating an array of Hexa colors with some random colors. Next, we will target the button using getElementById(), to this we will pass the id of the button changecolor.




Next, we will attach a click event to the button using addEventListener(), inside this method we will call another method which is changeBackgroundColor().

This method is responsible for generating the random number and picks the color from a from based on an index colors[randomNumber].

Finally, we will access the body style using document.body.style.background and assign the color to it.

Methods Used


  • getElementById(id): Using this we can target the element by passing the element id.
  • addEventListener(event, callback): We can attach an event to an element. The first parameter is the name of the event, the second parameter is a callback function.
  • Math.random(): This will generate a random number between 0 to 1
  • Math.floor(): This will decrease the value to the nearest integer number

That’s all for this now, I hope you guys enjoyed this post. If you like this post, then please share this with your friends and colleagues.



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

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