Using jQuery to change hover colour (from array)?
I was wondering if it were possible to use jQuery to change the colour of a link when hovered, g开发者_开发技巧etting the colour randomly from an array? I have the following but not sure how to grab the random colour.. This might be SUPER easy but I can't seem to work it out..
var colors = Array("#fb2900", "#ff7800", "#fff43b", "#8dfa30", "#01c86a", "#00d7b2", "#0092e3", "#002f7e", "#390e73");
$("ul.menu li a").hover(function(){
$(this).css("color","#f0f"); //random colour would be going here
}, function() {
$(this).css("color","#ffffff");
});
Why not try something like:
var colors = Array("#fb2900", "#ff7800", "#fff43b", "#8dfa30", "#01c86a", "#00d7b2", "#0092e3", "#002f7e", "#390e73"), idx;
$("ul.menu li a").hover(function(){
idx = Math.floor(Math.random() * colors.length); // Pick random index
$(this).css("color", colors[idx]);
}, function() {
$(this).css("color","#ffffff");
});
Try Math.random() and use that value to fetch an array index.you might also have to make sure that u don't access an array out of bound .
Here you go
$(this).css("color",colors[Math.floor(Math.random() * colors.length)]);
Also make sure your js is in a $(document).ready();
var colors = ["#fb2900", "#ff7800", "#fff43b", "#8dfa30", "#01c86a", "#00d7b2", "#0092e3", "#002f7e", "#390e73"];
$("ul.menu li a").hover(function(){
var color = colors[Math.floor(Math.random() * colors.length)];
$(this).css("color",color); //random colour would be going here
}, function() {
$(this).css("color","#ffffff");
});
You can use the Math Javascript Object
var random_number = Math.floor(Math.random()*9)
var random_color = Array[random_number]
$(this).css("color","random_color);
Use Range Random number function ~
function GetRangeRandom(min, max)
{
return (Math.floor((max-min-1)*Math.random()) + min);
}
精彩评论