Tricky Tricks ›› Programming Tricks ›› Javascript Tricks ›› User Selectable Background Color Source Code

User Selectable Background Color Source Code

Javascript Tricks

User Selectable Background Color Source Code:

Event handlers (in this case button onClick handlers) can change the document background color.

 <script>
 
 function newbg_color(color) {
    stop_annoying_me();
    document.bgColor=color;
 }
 
 // this one cycles through colors (really annoying!)
 var annoy=0;
 var cnt=0;
 
 function cycle () {
    annoy=1;
    annoy_me();
 }
   
 // turns off the annoying color cycling.
 function stop_annoying_me() {
    annoy=0;
 }
 
 // create and initialize an array that holds the color names we will
 // cycle through (to be annoying).
  
 var colors = new Array("red", "blue", "white", "green", "yellow", "purple");
 
 // changes the background color to colors[cnt] (cnt is a global).
 // also schedules the next run of this function 1/2 second from now
 // (5000 ms)
 function annoy_me( ) {
    if (annoy==1) {   
       document.bgColor = colors[cnt];
       cnt++;
       if (cnt==colors.length) {
          cnt=0;
       }
       window.setTimeout("annoy_me()",500);
    }
 }
 
 </script>
 
 <div>
 
 <center>
 
 <h2 style="text-align:center">Select your favorite background color:</h2>
 
 
 <table cellspacing="0" cellpadding="10">
 <tr>
 
 <td>
 <input type="button" class="but" value="red" style="background-color:red;"
        onClick="newbg_color('red');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="blue" style="background-color:blue;"
        onClick="newbg_color('blue');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="white" style="background-color:white;"
        onClick="newbg_color('white');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="purple" style="background-color:purple;"
        onClick="newbg_color('purple');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="green" style="background-color:green;"
        onClick="newbg_color('green');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="yellow" style="background-color:yellow;"
        onClick="newbg_color('yellow');"/>
 </td>
 
 <td>
 <input type="button" class="but" value="annoy me" style="background-color:gray;"
        onClick="cycle();"/>
 </td>
 </tr></table>
 </center>
 
 </div>
 
 

Partners