views:

101

answers:

1

I'm trying to get a reference to cell and it appears null. If I'm understanding it correctly, I should be able to reference the variable. Correct?

$('td[someAttr]').mouseenter(function(cell) {
    var timeoutId = setTimeout(function() {
        // what should variable cell be? 
    }, 1000);
});

OR

$('td[someAttr]').mouseenter(function(cell) {
    var timeoutId = setTimeout(function() {
        // what should variable cell be? 
    }, 1000, cell);
});

UPDATE: This was obvious but the reason I asked this was because cell.pageX would be undefined if you had:

$('td[someAttr]').mouseenter(function() {
    var cell = this; //
    var timeoutId = setTimeout(function() {
        alert(cell.pageX); // cell.pageX will return null 
    }, 1000);
});

However, if you had:

$('td[someAttr]').mouseenter(function(cell) {
    alert(cell.pageX); // works fine as cell.pageX will have correct value.
});
+4  A: 

The context of the event handler is set to the element that triggered the event. You can get at it this way:

$('td[someAttr]').mouseenter(function() {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName);
    }, 1000);
});

You may also want to wrap it as a jQuery object as well: var cell = $(this);

UPDATE: The first argument is the event object, not the element. The element is set as the context of the callback (i.e. this) and you can get access to the event object in exactly the way that you were in your example:

$('td[someAttr]').mouseenter(function(event) {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName + ' ' + event.pageX);
    }, 1000);
});

Note that the "cell" element is also accessible as "event.target".

Prestaul
This was obvious but the reason I asked this was because cell.pageX would be undefined, I'll post an update and show you what I mean.
Floetic