Reputation: 752
$(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
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
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
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