jQuery .on("click") - alternative to .live()

10k Views Asked by At

In my project I am appending several buttons to a div:

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn_edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>");

and then listen for a click with the following code:

$(".tab-content").on("click",".btn-edit",function(){
  console.log('edit');
});

Why is this not working? I am used to use .live() but it has been deprecated.

Thanks.

2

There are 2 best solutions below

2
On BEST ANSWER

In your markup you have btn_edit and in your jQuery you have btn-edit.

Change your markup class to match the jQuery selector, like this:

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn-edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>");
2
On

The reason your method didn't work (aside from what was pointed out about btn-edit) could be because you were attempting to bind an event to an element that didn't actually exist in the DOM until after it was appended, there used to be LIVE which has been depreciated but you can do this instead:

//bind the event to the document which always exists and specify the selector
//as the second argument 
$(document).on("click",".tab-content .btn-edit",function(){
    console.log('edit');
});

Hope this helps see jQueries on documentation here for more help.