user727836
user727836

Reputation:

How to alter CSS styles with Javascript?

I have an Array like this:

var colors = {
1: '#FFFF00',
2: '#FF0000',
3: '#80FF00',
4: '#00FFFF',
5: '#FF00FF'
}; 

And Javascript like this:

var color = Math.floor(Math.random()*5)+1;
if(color == document.getElementById('awards').style.borderColor) {
    var color = Math.floor(Math.random()*5)+1;
}
else {
document.getElementById('awards').style.borderColor = color;
}

But my Javascript isn't working.

Upvotes: 2

Views: 559

Answers (3)

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

If you want to write dynamic CSS and write some code and logic inside, I recommend to take a look at http://www.dotlesscss.org/
I know it will take time to learn, but I proffered to mention about it, may be it help someone.

Upvotes: 0

alex
alex

Reputation: 490143

You are generating an index, but not subscripting the array.

jsFiddle.

Also, to nitpick, {} creates an object with properties, technically not an Array (though an Array is an object). [] is the literal notation for an Array in JavaScript.

Update

Here is maybe how I'd have written it, if that helps...

var getRandomColor = function() {
    var colors = [
        '#FFFF00',
        '#FF0000',
        '#80FF00',
        '#00FFFF',
        '#FF00FF'
        ];
    return colors[Math.floor(Math.random() * colors.length) + 1];
}

var color = getRandomColor(),
    element = document.getElementById('awards'),
    borderColor = element.style.borderColor;

if (color == borderColor) {
    color = getRandomColor();
}
else {
    element.style.borderColor = color;
}

jsFiddle.

Upvotes: 2

CarlosZ
CarlosZ

Reputation: 8669

You are not really getting the random color, just getting the random number in a range, you'll need to change your code to this:

var color = colors[(Math.floor(Math.random() * 5) + 1).toString()];
if(color == document.getElementById('awards').style.borderColor) {
    var color = colors[(Math.floor(Math.random() * 5) + 1).toString()];
}
else {
    document.getElementById('awards').style.borderColor = color;
}

Upvotes: 0

Related Questions