2

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Talon I hope you didn't think that was my intention :) It's easy to forget the little things!
No no. I know you meant well. Thank you.
0

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

1 Comment

Each color has a number assigned to it. So 5 = #FF00FF. Anyway, @alex figured it out.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.