How to change the background color after clicking the button in JavaScript ?

End Result

Today in this tutorial we are going to learn how to change background color in html using a button and JavaScript.

Before jump into tutorial, we need three files. I ‘m using VS Code , we are free to to use any code editor. The three files are:-

  1. home.html
  2. style.css
  3. main.js

You can style it far more better than me, but just to make it simple, have done it. I just keep the CSS much more easy and simple to understand for beginners and put more focus on JavaScript part.

Home Page :

For designing the home page, I used two <div> </div> tags to make two containers with ids. And add a property of center.

You need to add your style.css & main.js file in the home.html file.

The process is shown below.

Full Code for home.html file:

Style for home Page:

Full Code for style.css file:

Well, if you have done till now everything correctly, and you open the home.html file, then you have faced the web page something like this as mentioned below:

So right now we have two container, with a text and button. So let’s start the JavaScript part of this project.

JavaScript:

Full Code for main.js file :

So whenever the user clicks the button the color will be changed. So I have created an array of color. Using document.getElementById() , I am collecting the id of the button and an event Listener that enables to run a function. In that function, we are selecting a random color from the color array and then change the container style property.

And if you are doing everything all right, Congregation!! we made it!!.

I’m a Web Developer and Content Creator on Youtube . To know more about me lets connect : https://ankandaslinks.netlify.app/