redconservatory
redconservatory

Reputation: 21934

jquery click, remove

if I add a jQuery click handler to an object, i.e.

$('#my-link').click(function() {
// stuff
});

But then I remove the link from my page, do I have to remove my click handler, and if so, how do I go about that?

Upvotes: 0

Views: 432

Answers (4)

simshaun
simshaun

Reputation: 21476

Nope. Once the element is removed from the DOM, the onclick event is removed with it.

Only if the click event is being delegated through the document element would it need to be removed manually, and jQuery takes care of this for you as long as you are using jQuery's .remove() method.

Upvotes: 0

thecodeassassin
thecodeassassin

Reputation: 836

The click handler binds on the element when it gets selected by the selector engine. When you remove the link from the page the action won't be bound so there wont be a problem.

If you remove the link by code you can use the unbind('click') function to remove the actual action.

Upvotes: 0

maxedison
maxedison

Reputation: 17573

No, you don't need to. From the jQuery documentation:

Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Upvotes: 3

Mark Brown
Mark Brown

Reputation: 12544

Per the jQuery documentation remove() removes all events bound to the element: http://api.jquery.com/remove/

Upvotes: 0

Related Questions