When using jQuery.load
to dynamically load HTML content into a webpage, what is the best way to "rebind" any handlers?
Normally you bind handlers in jQuery.ready
, but they obviously don't work on newly loaded content. This is for handlers used both outside and inside the loaded content, so just binding them in the load
success function is not really nice.
When subscribing to those handlers you could use the .on
function which allows you to subscribe to even non existing yet DOM elements and when they are added the subscription will be done. The .on
function was introduced in jQuery 1.7. If you are using an older version you could use the .delegate
function to achieve the same effect which was introduced in jQuery 1.4.2. And if you are using an even older version you could use the .live
method.
Here's an example of how you could subscribe to the click event of some element (existing or not yet existing that will be added in the future):
$('#someParentElement').on('click', '#someElement', function() {
});