2

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.

2
  • 1
    Are you positive? Where is your <script> tag (before or after the body)? Commented Jan 7, 2013 at 2:22
  • 1
    Not related to the error, but if you need to change the background color you should use style.backgroundColor instead of style.color. Commented Jan 7, 2013 at 2:36

2 Answers 2

4

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/

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

7 Comments

Your script will have errors @Blender, because if you get a number less then 6 characters the color wont change or changes wrong.
@SantoshKumar: Sorry, load should be onload.
@Blender still with the same problem, will not aways have 6 characters. You can complete it using RegExp, or use another like solution like what I did.
What if I want to change background color of body?
@SantoshKumar Use document.body.style.backgroundColor = random_color() on the onload callback
|
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.