Reputation: 507
I'm creating and removing HTML from inside a div with jQuery (shopping cart, adding/removing items). I need to access the .click()
event of a link inside this div, but it only works when the page first loads - after that link is removed then re-added it doesn't respond to any jQuery events.
I've tried functions both inside and outside of $j(document).ready(function() {}
. How can I make events work on this link again after re-creation?
Upvotes: 0
Views: 67
Reputation: 2321
The .click()
event only works for elements that are present with the function is called. You need to look into using either .live()
or .delegate()
to attach listeners to elements that are dynamically created after $(document).ready()
Upvotes: 1
Reputation: 35253
Try using .detach()
instead of .remove()
, that will keep the events. Alternatively use event delegation.
Upvotes: 0
Reputation: 76003
Use .delegate()
instead of .click()
(which is short-hand for .bind('click')
):
$(<root-element>).delegate('a', function () {...});
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
Source: http://api.jquery.com/delegate/
The <root-element>
can be the document
element or if you know an element that is always present that is a descendant of the document
element it is best to use that element.
Upvotes: 2
Reputation: 10221
You need to either reattach the event every time you overwrite the content of your container div or set handler using live/delegate/on
depending on the version of jQuery you use.
Second method is in general more elegant, but has drawbacks. In particular you cannot cancel the default action from cascaded even attached to the container.
Upvotes: 1