I have a div inside a table cell. When I click in the table cell on the div, the click event isn’t trigged, it seems like that table cell is on top of the div? I have tried adjusting the z-index to no avail.
Example row:
<tr ><td><div class="test" style='width:64px; height:22px; margin:0 auto; z-index:1000'></div></td></tr>
Example jquery:
$('.test').click(function(){
console.log($(this), 'this');
});
Update: The div in my table row is added dynamically after the document is loaded and the jquery code is in the .ready part of my code perhaps that is why?
The key to your question is in your recent comment:
When you run your code, which hooks up the handler directly on elements, it will hook the
clickevent only on elements matching the selector that already exist. Elements you add later won’t be hooked up.If you want your code to handle elements that are added later, you probably want to use event delegation. jQuery supports this via the
delegatefunction or (if you’re using 1.7 or later) the delegating form ofon:What those do is hook the
clickevent on some container (in your case you might use the table), and when the click reaches that container, jQuery checks to see if it traveled through an element matching the selector you give. If so, jQuery fires the event as though you’d hooked click on the element itself.Here’s an example (live copy | live source):
HTML:
JavaScript:
Alternately, of course, you can always hook up the event on the element when you’re adding it. But if you’re adding and subtracting elements from a container, event delegation is usually (not always) the way to handle events on them.