views:

145

answers:

2

In a jquery hover event I use the following code to drop down a menu:

clearTimeout(hTimeout);
$('#lowermenu').queue('fx', []);
$('#menucenter .current').removeClass('current');
$(this).children('a').addClass('current');        
dTimeout = setTimeout(function($item){slidelower($item)}, 200, $(this)); // This is the bad line

function slidelower($li)
{
    $li.addClass('dropping');
    $lowermenu = $li.children('ul').clone();
    $('#lowermenu:not(:animated)').empty().append($lowermenu).slideDown();
    $('#lowermenu > ul > li:not(:animated)').hover(function()
    {                      
        $(this).children('ul:hidden').css('top', 'auto').slideDown();
    }, function()
    {
        $(this).children('ul:visible').slideUp();
    });
}

I get the following error:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.3; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; OfficeLiveConnector.1.3; OfficeLivePatch.0.0) Timestamp: Sat, 14 Nov 2009 11:12:46 UTC

Message: 'undefined' is null or not an object

Line: 81

Char: 25

Code: 0

URI: [the url was here]

I suspect that it's caused by the setTimeout - I am passing in a third parameter as an argument for the anonymous function. That anonymous function calls a function with a closure.

Can anyone help?

+1  A: 
$(this).children('a').addClass('current');   
var that = this;     
dTimeout = setTimeout(function($item){slidelower($item)}, 200, that); // This is the bad line

setTimeout is owned by the window object, therefore this refers to window. Save the reference to the outer context by caching it with a 'that' variable.

meder
Thanks meder, your answer helped, but I wasnt able to pass a usable object through, even trying many permutations of that method. Thank you, though.
Antony Carthy
Ok I still have trouble: setTimeout(function(theid){window.console.log(theid)}, 200, 'test'); This is outputting to the console "undefined". What am I doing wrong?
Antony Carthy
Full source code or a demo would help.
meder
A timeout is called with no arguments, so there is no `theid` being passed into your function, hence it is `undefined`. You need to use a closure to keep a copy of a variable, or `function.bind` (in future, or now with suitable prototype hacking).
bobince
A: 

OK, I found the problem. setTimeout in IE doesnt support the additional parameters:

https://developer.mozilla.org/en/window.setTimeout

Mission aborted.

Antony Carthy