Forum Moderators: open

Message Too Old, No Replies

Trouble with timeout function

         

sgietz

5:37 pm on Jan 17, 2007 (gmt 0)

10+ Year Member



Hi,

I'm trying to show a div when a button is clicked and the hiding it a half-second after the button loses focus. I can show it fine, but the timeout function doesn't work.

Here's the code:

===============================================================
<script type="text/javascript">
function doit(div,func) {
var d = document.getElementById(div);
var f = parseInt(func);

if (f==1) {
d.style.display = 'block';
} else if (f==0) {
setTimeout("d.style.display='none';",500,"JavaScript");
}
}
</script>

<div id="box">
<a href="#" class="link1">Some Link Here</a>
<a href="" class="link1">Some Link Here</a>
<a href="#" class="link1">Some Link Here</a>
<a href="#" class="link1">Some Link Here</a>
</div>

<form id="form1" method="post">
<input type="button" id="bt" value="Show Me" onfocus="doit('box',1);" onblur="doit('box',0);" />
</form>
===============================================================

The error I get onblur is 'd' is undefined.

Fotiman

7:25 pm on Jan 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



setTimeout works in the scope of the window object. In your example, you're trying to execute this:

d.style.display='none'

But in the scope of the window object, there is no such thing as 'd' because it's only in the scope of the doit function.

Try this:


<script type="text/javascript">
// Define global variable, which is in the window scope
var d;
function doit(div,func) {
d = document.getElementById(div);
var f = parseInt(func);
if (f==1) {
d.style.display = 'block';
} else if (f==0) {
setTimeout( "d.style.display='none'",500);
}
}
</script>

[edited by: Fotiman at 7:26 pm (utc) on Jan. 17, 2007]

sgietz

7:36 pm on Jan 17, 2007 (gmt 0)

10+ Year Member



Ahh. That works perfectly. Thanks :)