Forum Moderators: open

Message Too Old, No Replies

variable undefined

         

jackvull

10:42 am on Oct 7, 2005 (gmt 0)

10+ Year Member



I get a DJDiv is undefined error with the following:
function brieflyHideMenus(varDJID) {
var DJDiv = 'DJdiv' + varDJID;
alert(DJDiv);
document.getElementById(DJDiv).style.visibility='hidden';

setTimeout("document.getElementById(DJDiv).style.visibility='visible'", 5000)
}

It works up to the visibility.hidden part but then as soon as the stuff starts to run after 5 seconds (timout), the error appears.

Any ideas?
Thanks.

kaled

11:03 am on Oct 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Code executed by setTimeout() is global in scope - it does not execute within the function. i.e. unless there is a global variable DJDiv that can act as a parameter the code will fail.

Kaled.

jackvull

11:10 am on Oct 7, 2005 (gmt 0)

10+ Year Member



Thanks that did it.
Variable scope annoys the **** out of me.

Bernard Marx

12:15 pm on Oct 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



kaled is right. Yet I don't believe he was actually suggesting you should use a global variable for this purpose - he was just saying that that is what the command is expecting
- Am I right, kaled?

There are two solutions to this that don't require a global variable.
The second is my preferred, because it does away with string nonsense in the timer.

function brieflyHideMenus(varDJID) 
{
var id = 'DJdiv' + varDJID;
document.getElementById(id).style.visibility='hidden';
// note single quotes on id
setTimeout("document.getElementById('"+id+'").style.visibility='visible'", 5000);
}

function brieflyHideMenus(varDJID)
{
var div = document.getElementById('DJdiv' + varDJID);
div.style.visibility='hidden';
setTimeout( function(){div.style.visibility='visible'}, 5000);
}

kaled

1:20 pm on Oct 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As Bernard said, I was explaining the cause rather than suggesting a solution.

As a general rule, when answering questions, I tend to take the "homework" approach. That is so say, I try to point people in the right direction rather than solve the problem.

Kaled.