Genadinik
Genadinik

Reputation: 18639

How to do a live binding of a click handler in jQuery

I have a click event handler that looks like this:

$('#show_existing_suggestions').click(function()

But after some AJAX calls, it is no longer recognized by jQuery. Is there a way to do a live binding of that click handler? I think the reshuffling of the HTML is messing it up.

Thanks!!!

Upvotes: 2

Views: 81

Answers (3)

polyhedron
polyhedron

Reputation: 1590

$('#show_existing_suggestions').live('click',function(){});

http://api.jquery.com/live/

Upvotes: 1

Greg Pettit
Greg Pettit

Reputation: 10830

If you are using .on() (1.7 forward), then to reproduce this as a "live" binding, you need to call it on the document, not on the clickable element:

$(document).on('click', '#show_existing_suggestions', function() { ... });

But since you're already this far along, you should take it a step further and delegate not to the document but to an ancestor more deeply nested if possible. The syntax is the same, the selector is different:

$('#someElement').on('click', '#show_existing_suggestions', function() { ... });

Where #someElement is any ancestor of show_existing_suggestions that you do not forsee ever being destroyed. Could conceivably be the next element up in the tree, but it could be a section wrapper or even page wrapper (what site these days doesn't have a page wrapper?)

Upvotes: 0

alex
alex

Reputation: 490413

$('#show_existing_suggestions').live('click', function() { ... });

As of jQuery 1.7, live() has been deprecated (thanks Vikk). Use on() instead.

Upvotes: 4

Related Questions