ehabd
ehabd

Reputation: 1077

Click event on element (displayed only on hover) is not triggered

I can't get an event to trigger when you click on an element, and this element is only displayed when you hover of a td element.

//Hovering over a td element displayed a Span
$('td').hover(
    function() {$(this).append('<span class="editCell">hello</span>')}, 
    function() {$(this).find('span:last').remove()}
)

//Clicking on that span, it's supposed to trigger alert. But it doesn't. 

$('.editCell').click( function(){

    alert('hello');
})

Upvotes: 1

Views: 156

Answers (2)

Rafael Adel
Rafael Adel

Reputation: 7759

Because .click() event doesn't work on dynamically added content.

Use .on() instead

$("td").on("click", ".editCell" ,function(){

});
  • The first parameter is the event you want to bind.
  • The second parameter is the selector, it filters all the elements in td and bind click event only to that selector.
  • The third parameter is the function to call.

The above is called delegated-events.

You also can do it like this :

$(".editCell").on("click",function(){

});

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

This is because the editCell element is being appended after page load. You need to delegate the event to the nearest static element. Try this:

$("td").on("click", ".editCell", function() {
    alert("hello");
});

The td selector is still a little broad though, you should put an id on the closest parent of editCell for the sake of performance.

Upvotes: 0

Related Questions