Wondering if anybody could help with what seems a very simple problem but is taxing for this noob.

I set myself the task of creating a button which, when pressed, switches the background color randomly. It seems to work well enough but the random number it works from only generates once at page load.

As a workaround, I added a second 'Reset Page' button, but I really want just one button that switches the page color every time you prod it. Any ideas how to reset the random number to achieve this?

Here's the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/xml; charset=utf-8" />
    <title>randomBackground.html</title>
    
  </head>
  
  <body>
  	
	<h1>Click the button to change the color</h1>
    <form action = "">
      <fieldset>
        <input type = "button"
               value = "Click Me"
               onclick = "changeColor('color')"/>
              
             
	    <input type= "button" 
				 value = "Reset color"
                 onclick = "reloadPage()" />
      </fieldset> 
    </form>
	
  	<script type = "text/javascript">
      //<![CDATA[
	  
	         
		var number = Math.random();
	  	
	  	var biggerNumber = number * 6;
	  	
	  	var randomnumber = Math.ceil(biggerNumber);
	  
	  function changeColor(color){
	    
		
	  	if (randomnumber == 1) {
	  		(document.body.style.backgroundColor = "olive");
	  	}
	  	else 
	  		if (randomnumber == 2) {
	  			(document.body.style.backgroundColor = "blue");
	  		}
	  		else 
	  			if (randomnumber == 3) {
	  				(document.body.style.backgroundColor = "red");
	  			}
	  			else 
	  				if (randomnumber == 4) {
	  					(document.body.style.backgroundColor = "yellow");
	  				}
	  				else 
	  					if (randomnumber == 5) {
	  						(document.body.style.backgroundColor = "maroon");
	  					}
	  					else 
	  						if (randomnumber == 6) {
	  							(document.body.style.backgroundColor = "silver");
	  						}
							
	  }
function reloadPage()
  {
  window.location.reload()
  }
	 	  	

	//]]>

    </script>
   </body>
</html>

Just figured it out.

I needed the random number generator INSIDE the change color function rather than outside it.

This question has already been answered. Start a new discussion instead.