Paul Browne
Paul Browne

Reputation: 752

Re-generate random number on Event

$(document).ready(function() {
  var randomRed = Math.floor(Math.random() * 255);
  var randomGreen = Math.floor(Math.random() * 255);
  var randomBlue = Math.floor(Math.random() * 255);
  $('p').mouseover(function() {
      $('p').css('color', 'rgb(' + randomGreen + ',' + randomBlue + ',' + randomRed + ')');
  });
  $('p').mouseout(function() {
      $('p').css('color', 'black');
  });
});​

I have the above code which generates a random color on mouseover, then returns it to black on mouseout, which works fine. However it generates the same random color on every mouseover.

How do I make it so that it generates a different random color on every mouseover event??

Upvotes: 1

Views: 195

Answers (3)

Miroslav
Miroslav

Reputation: 1960

This is because you generating the color only once when the document loads instead of on hover event:

$(document).ready(function() {
    $('p').mouseover(function() {
        var randomRed = Math.floor(Math.random() * 255);
        var randomGreen = Math.floor(Math.random() * 255);
        var randomBlue = Math.floor(Math.random() * 255);
        $('p').css('color', 'rgb(' + randomGreen + ',' + randomBlue + ',' + randomRed + ')');
    });
    $('p').mouseout(function() {
        $('p').css('color', 'black');
    });
});

Upvotes: 1

GautamD31
GautamD31

Reputation: 28753

Try like this

$(document).ready(function() {
function randomNumber(){
return  Math.floor(Math.random() * 255)
}

$('p').mouseover(function() {
    $('p').css('color', 'rgb(' + randomNumber()+ ',' + randomNumber()+ ',' +     randomNumber()+ ')');
});
$('p').mouseout(function() {
      $('p').css('color', 'black');
    });
});

Upvotes: 0

sdespont
sdespont

Reputation: 14025

Just declare the number generation as function and call it in your events :

$(document).ready(function() {
    function randomNumber(){
        return  Math.floor(Math.random() * 255)
    }

    $('p').mouseover(function() {
        $('p').css('color', 'rgb(' + randomNumber()+ ',' + randomNumber()+ ',' + randomNumber()+ ')');
    });
    $('p').mouseout(function() {
        $('p').css('color', 'black');
    });
});

You could also simplify your events definition using .hover() : http://api.jquery.com/hover/

Upvotes: 0

Related Questions