views:

405

answers:

3

Can anyone tell me why this isn't working?

function changeBG(element_id){
     document.getElementById(element_id).className= "arrowActive";
     setTimeout("document.getElementById("+element_id+").className= 'arrow'", 300);
}

In firebug I get an error saying that the element_id passed to setTimeout() is not defined.

+2  A: 

Try:

setTimeout("document.getElementById('" + element_id + "').className= 'arrow'", 300);

Notice that I added quotes to the string parameter you're passing to getElementById.

Ken Browning
+4  A: 

The variable element_id will be a string, so your timeout code will look like:

document.getElementById(myId).className = ...

Notice that myId should be in quotes, but it's not.

A better way is to use a closure, like this:

function changeBG(element_id)
{
        var elm = document.getElementById(element_id);
        elm.className = "arrowActive";
        setTimeout(function() { elm.className= 'arrow'; }, 300);
}

It should be noted that passing the code in a a string is not recommended.

Greg
+1  A: 

The best way to do this is with a closure

function changeBG(element_id)
{
        var elem = document.getElementById(element_id);
        elem.className= "arrowActive";
        setTimeout( function(e)
        {
                return function()
                {
                        e.className = 'arrow';
                }
        }( elem ), 300);
}
Peter Bailey