In JavaScript let visitors change background color with the click of a button.  There are more advanced ways to do this however I am going to show you something very simple. The div classes that I will target on this website are site, site-content and entry-content. If you look over in the sidebar to the right you will see the button that will change the background on this website to black and the text to white instantaneously.

JavaScript Let Visitors Change Background Color

Here is the JavaScript code that is making this all happen. First I am going to set up the button and call an onClick event so that when the button is pushed it will call the function.

Button Code to Call Function

<button type="button"
onclick="changeColor()">
Change To Black Background!</button>

The JavaScript Function to Change Text Color and Background Color

I set up my three different div classes and stored them in JavaScript Variables x,y and z. I then stored everything into a function that gets called on an onClick Event.
<button type="button" 
onclick="changeColor()">
Change To Black Background!</button>


<script>
function changeColor() {
    var x = document.getElementsByClassName("site");
    x[0].style.background = 'black';
    x[0].style.color= 'white';

var y = document.getElementsByClassName("site-content");
    y[0].style.background = 'black';
    y[0].style.color= 'white';

var z = document.getElementsByClassName("entry-content");
    z[0].style.background = 'black';
    z[0].style.color= 'white';
}
</script>


Sign Up To Comment