JavaScript Let Visitors Change Background Color

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

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

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.

Only cool people share!

[code]<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>[/code]

JavaScript Let Visitors Change Background Color was last modified: May 14th, 2015 by Maximus Mccullough
Summary
JavaScript Let Visitors Change Background Color
Article Name
JavaScript Let Visitors Change Background Color
Description
In JavaScript let visitors change background color with the click of a button. There are more advanced ways to do this however this is a simple way to lean
Author
JavaScript-Let-Visitors-Change-Background-Color-1

2 Comments

  • Mike says:

    Works to change to dark but does not work to change back to original color. 😐 But thanks anyway.

    • Sure it works. Your site might have different class names than mine. Change the class name to make it match your site and it will work. Change the site, site-content, and entry-content to match your div’s and it will work.

      To change the color back just set up another button and another function. [code]<button type="button"
      onclick="changeColorBack()">
      Change To Black Background!</button>
      <script>
      function changeColorBack() {
      var x = document.getElementsByClassName("site");
      x[0].style.background = ‘white’;
      x[0].style.color= ‘black’;
      </script>
      [/code]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.