Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 Arrayis 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.

Solution 2:

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

Solution 3:

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.

Post a Comment for "How To Alter Css Styles With Javascript?"