mike44
mike44

Reputation: 812

Binding events to table cells using jQuery

This is my markup:

<div id="divContainer">
    <div>
        <table></table>
    </div>
    <div>
        <table></table>
    </div>
    ....
</div>

I need to to register mouseenter event on all tds of all the tables (that are present inside each div).

$(document).ready(function () {
    $allTds = $('#divContainer').find("tr").find("td");
    ...
    SomeFunction();
});

function SomeFunction(){
   $allTds.on({
       mouseenter: function (e) {
           alert('hover');
       }
   });
}

But I don't get any alerts.

Upvotes: 0

Views: 938

Answers (2)

Phil
Phil

Reputation: 164895

The reason your event handlers aren't being bound is that the <td> elements don't exist when you enter the document ready handler.

You should use event delegation for this. For example

window.jQuery(function($) {
    $('#divContainer').on({
        mouseenter: function(e) {
            alert('hover');
        }
    }, 'td');
});

This way, it's the #divContainer element that listens for the events and acts on them if they originate from a <td>.

See http://api.jquery.com/on/#direct-and-delegated-events

You also had a scoping problem where the $allTds variable is only defined in the document ready handler and is not in scope of the SomeFunction function.

Upvotes: 1

Imperative
Imperative

Reputation: 3183

They way you apply the event listener is weird.

$('#divContainer').on('mouseenter','td',function() {
    alert('mouse entered');
});

Also: It's good that you cache the td elements, but why don't you stick with something more simple?

$allTd = $('#divContainer td');

Upvotes: 3

Related Questions