LiveZilla Live Help

Opal Creations Blog | A bit about what we do and what we know!

TAG | javascript

This JavaScript function provides a simple script to generate a random HEX colour code that can be used on any DOM element. A simple call to the function “genHEX()” will return a 6 character string that changes everytime. This is useful if you want an element to be a different colour on each page load.

The Code

Below is the code, documentation is in the form of comments in the code.

function genHex(){
    // Make a new array with all available HEX options.
    var colours = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
    // Make variable to hold 6 character HEX array
    digit = new Array(5);
    colour="";
    for (i=0;i<6;i++){
        // Loop through 6 times, randomising the letter added to the array
        digit[i]=colours[Math.round(Math.random()*14)];
        colour = colour+digit[i];
    }
    // Returns like "a10bc5". It is likely that you may need to add a "#".
    return colour;
}

· · ·

Theme Design by devolux.nh2.me