Santosh Kumar
Santosh Kumar

Reputation: 27875

How to set CSS value with JavaScript?

I want to change the background color of an HTML element whose ID is foo. I have this code at present:

var hexcode = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');

// this chooses a random value from the array hexcode
var ranval = function() {
    return hexcode[Math.floor(Math.random()*hexcode.length)];
}

// six ranval() are put together to get color
var colorname = "#" + ranval() + ranval() + ranval() + ranval() + ranval() + ranval();

// trying to put the value on the background of element with "foo" ID.
document.getElementById("foo").style.color = colorname;

This code is throwing this error:

Uncaught TypeError: Cannot read property 'style' of null 

I'm sure that ID foo exists.

Upvotes: 2

Views: 869

Answers (2)

Gabriel Gartz
Gabriel Gartz

Reputation: 2870

The simple way to fix your code is:

var random_color = function() {
    function randomHex() {
        return Math.floor(Math.random() * 15).toString(16);
    }
    var str = '#';
    for(var i = 6; i--;) {
        str += randomHex();
    }
    return str;
}


window.onload = function() {
    // For your body background color
    document.body.style.backgroundColor = random_color();

    // For your foo element TEXT color
    document.getElementById("foo").style.color = random_color();

    // For your foo element BACKGROUND color
    document.getElementById("foo").style.backgroundColor = random_color();
};

Upvotes: 2

Blender
Blender

Reputation: 298066

Your error occurs because you're trying to access your element before the DOM is ready. Wait for the window to load before accessing it:

// Credit: http://paulirish.com/2009/random-hex-color-code-snippets/

function random_color() {
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}

window.onload = function() {
    document.getElementById("foo").style.backgroundColor = random_color();
};

Demo: http://jsfiddle.net/Blender/xQure/1/

Upvotes: 4

Related Questions