JQuery Keeping Click Handler when Updating Content - Live Binding

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

If you are using jQuery and attaching click handlers etc to elements as part of your document ready block, you may find you are losing those handlers if you update the page with Javascript after load.

For example if you have some kind of slide show which involves redrawing the contents of a div, you might find that the click handlers you had attached to the links of class ‘slideshow-link’ stop working.

Of course you can reattach handlers manually after dropping in your new HTML but that’s pretty messy.

A much nicer solution is this:

Instead of using

jQuery('.slideshow-link').click(function(){});

You can use

jQuery('.slideshow-link').live('click', function(){});

The Live method will keep the attachment to elements matching the selector now and in the future.

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

Gotta love jQuery ;)


Tags: javascripthtmljqueryupdatesolutioneventhandlerbindliveattachdommaintain