0

I am having trouble. I am looking to press a button and have a random number return into a text box. If the number is even I want to change the background color to Red, and if its odd I want to change the background color to black. I have it almost working,but it does not continue to change the background color when I keep pressing the button, it only does the first. Here is my code. Any help would be appreciated.

<script type="text/javascript">

function BackgroundEven(){
document.body.style.backgroundColor="#DA0505";
}
function BackgroundOdd(){
document.body.style.backgroundColor="#000000";
}

function Random() {

return Math.floor(Math.random()*37);
}

var rando= Random();
function Change(){
if(rando%2 == 0)
{
BackgroundEven();
} 
else{
BackgroundOdd();
}
}
}

</script>

<input type="text" name="Result" value="" id="Random" size="5"/>
<input type="button" value="Spin" onclick="document.getElementById('Random').value=Random();Change();" />
</input>
1
  • wrap up your onclick into a function (much easier to read). but the issue is that the var rando is only set once when the page loads Commented Nov 17, 2013 at 0:08

3 Answers 3

1

You're generating one random number in the onclick, then using a newly generated random number for the odd/even check. You need to ensure you're checking against the random number that was stuffed into the input:

<input type="button" value="Spin" onclick="Change(document.getElementById('Random').value=Random());" />

function Change(currentNum) {
  if(currentNum % 2 == 0)
    BackgroundEven();
  else
    BackgroundOdd();
}

Notice how I pass the newly assigned random number to the Change() function so it is operating on the same random number as was stuffed into the input.

Sign up to request clarification or add additional context in comments.

Comments

0

Try Math.floor(Math.random()*2);, for 0 or 1.

Comments

0

Try passing the random number into Change as an argument instead of relying on closure.

function Change(rando){
  if(rando%2 == 0) {
    BackgroundEven();
  } 
  else {
    BackgroundOdd();
  }
}

It's also not very pretty to call two or three functions at a time with onclick. Nowadays we would usually append a listener to the object as soon as the document has loaded. That said, to make your code a bit prettier...

function clickForRandom(){
  var rando = Random();
  document.getElementById('Random').value = rando;
  Change(rando)
}

<input type="button" value="Spin" onclick="clickForRandom()" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.