SoulieBaby
SoulieBaby

Reputation: 5471

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, getting 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");
});

Upvotes: 0

Views: 2487

Answers (6)

Jinbom Heo
Jinbom Heo

Reputation: 7400

Use Range Random number function ~

function GetRangeRandom(min, max)
{
    return (Math.floor((max-min-1)*Math.random()) + min);
}

Upvotes: 0

Nada Aldahleh
Nada Aldahleh

Reputation: 1308

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);

Upvotes: 0

generalhenry
generalhenry

Reputation: 17319

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");
});

Upvotes: 1

Horatio Alderaan
Horatio Alderaan

Reputation: 3284

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");
});

Upvotes: 1

superfro
superfro

Reputation: 3302

Here you go

$(this).css("color",colors[Math.floor(Math.random() * colors.length)]);

Also make sure your js is in a $(document).ready();

Upvotes: 1

Bunny Rabbit
Bunny Rabbit

Reputation: 8411

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 .

Upvotes: 1

Related Questions