tags:

views:

21

answers:

3

Hello everyone!

I'm trying to change element's background-color using random colors from an array. There is the code:

 $(document).ready(function(){

var randomColors = ['#00eeff','#fcff00','#9600ff'];
var rndNum = Math.floor(Math.random() * randomColors.length);

$("div.anyclass").hover(
        function() {
 $(this).css({'background-color' : 'randomColors[rndNum]'}) 
 }, 
        function() {
 $(this).css({'background-color' : '#fff'});
        });
});

So, it doesn't work, where is the problem?

+1  A: 

You just need to remove the quotes, like this:

$("div.anyclass").hover(function() {
   $(this).css({'background-color' : randomColors[rndNum]}) 
}, function() {
   $(this).css({'background-color' : '#fff'});
});

Currently it's trying to set the string as exactly 'randomColors[rndNum]', not the value of that entry in the array, e.g. '#00eeff'.

Nick Craver
+1  A: 

Change this line:

$(this).css({'background-color' : 'randomColors[rndNum]'}) 

to this:

$(this).css({'background-color' : randomColors[rndNum]}) 

The variable won't be expanded if it's within a string.

mway
+2  A: 

You need to remove quotes from 'randomColors[rndNum]' otherwise it becomes a mere string:

$(this).css({'background-color': randomColors[rndNum]}) 

OR

$(this).css({backgroundColor: randomColors[rndNum]}) 
Sarfraz