Scott
Scott

Reputation: 1127

Jquery .on not observing new elements that are added after load

I have the following jQuery code which watches for an ajax request and then shows / hides a spinner image when the request starts / ends.

This works fine on page load. However if I update part of the page with a new ajax link, this code no longer catches the ajax:before. Does anyone know if there is a solution to this without having to call unbind() and then re-call the code again?

$("*[data-spinner]").on('ajax:before', function(e) {
    $('#' + $(e.target).data('spinner')).show();
});

$("*[data-spinner]").on('ajax:complete', function(e) {
    $('#' + $(e.target).data('spinner')).hide();
});

Upvotes: 0

Views: 110

Answers (3)

Felipe Skinner
Felipe Skinner

Reputation: 16616

$(document).on('ajax:before', '*[data-spinner]', function(e) {
    $('#' + $(e.target).data('spinner')).show();
});

This is because jQuery binds its functions to the DOM on the pageload. If you try to bind your "data-spinner" that is not there yet jQuery will not find it and wont bind it.

However if you bind on document it can be found and we pass your '*[data-spinner]' as a 2nd parameter since its just a filter. jQuery will watch it only when you click something inside "document" so it will always be up-to-dated.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

It should be something like

$(document).on("ajax:before", "*[data-spinner]", function(){
    //...
});

Or you can use the parent element instead of document and it's better/faster, i.e.

$('#parent_element').on("ajax:before", "*[data-spinner]", function(){
    //...
});

The prototype is

.on( events [, selector ] [, data ], handler(eventObject) )

Read more on jQuery website.

Upvotes: 0

vinothini
vinothini

Reputation: 2604

Did you tried like

$("body").on("'ajax:before", "*[data-spinner]", function(){
 $('#' + $(e.target).data('spinner')).show();
});

$("body").on('ajax:complete', "*[data-spinner]", function(e) {
    $('#' + $(e.target).data('spinner')).hide();
});

Upvotes: 2

Related Questions