From looking at other posts I\'ve tried to add live() and on() to my code but the click function only works once and then wont work anymore. Can someone point out what I\'m
Events are bound to DOM nodes. If the DOM which you are binding to is removed the associated event will likely be removed too. You can fix this or you can make use of the "bubbling up" nature of DOM events. For example, say my HTML was this:
What I could do is bind to the #container
or to document
to listen to any click event and inspect the event's target to see if I want to take action. An example of that for the above HTML:
$('#container').on('click', function (event) {
var target = $(event.target);
if (target.hasClass('delete_me')) {
target.remove();
}
});
Which is the same as:
$('#container').on('click', '.delete_me', function (event) {
$(event.target).remove();
});
Or I can even listen on the document level:
$(document).on('click', '.delete_me', function (event) {
$(event.target).remove();
});
Here is a working example: http://jsfiddle.net/Kcapv/
Note that event.stopPropagation()
if used on a child node will stop the event bubbling up so if you try this approach you need to be careful to watch for use of stopPropagation.