Harry
Harry

Reputation: 1150

How do I assign a random colour to links?

Just wondering why my code isn't working. Am I doing this completely wrong?

window.onload = function random() {
    var links = document.getElementsByTagName('a');
    var colours = new Array("green","red","blue");
    var randomColour = colours[Math.floor(colours.length * Math.random())];
    for (a = 0; a < links.length; a++) {
        links[a].style.color = 'randomColour';
    }
}

Upvotes: 0

Views: 353

Answers (1)

Rob W
Rob W

Reputation: 349142

'randomColor' -> randomColor.
Use a variable instead of a quoted string. Also, to ensure that each link gets a random color, generate the color in the loop:

for (var a = 0; a < links.length; a++) {
    var randomColour = colours[Math.floor(colours.length * Math.random())];
    links[a].style.color = randomColour;
}

To minimize the delay between setting the color, and parsing the link, bind a DOMContentLoaded event, or simply paste the code at the end of the <body>:

http://jsfiddle.net/V6Chb/1/

<a>Test</a>
  ... 
<a>Test</a>
<script>
(function() { // <-- Anonymous function to not leak variables to the global scope
    var links = document.getElementsByTagName('a');
    var colours = ["green", "red", "blue"];
    for (var a = 0; a < links.length; a++) {
        var randomColour = colours[Math.floor(colours.length * Math.random())];
        links[a].style.color = randomColour;
    }
})();  

Upvotes: 1

Related Questions