Devin
Devin

Reputation: 2246

jQuery .on() not working with PJAX?

$("#img-switcher").on("switchImageEvent", function(event, triggerID){
    $(this).attr('src',triggerID);
});
$("#page-container").on("click", "img.img-switcher", function() {
    var newSRC = $(this).attr('src');
    $("#img-switcher").trigger("switchImageEvent", [newSRC]);
});

This code is not working for me with PJAX it seems. If I initially load a page, it selects the elements just fine and makes the change. However, as soon as I go to another page with PJAX, it will no longer select the element for the .on("click") action. Am I doing something wrong? I tried adding an alert before var newSRC to see if it was properly selecting the element with .on(), but it isn't. Any ideas?

Upvotes: 1

Views: 1066

Answers (1)

Krule
Krule

Reputation: 6476

Well since there is just this bit of code pulled out of context I would assume you are trying to use on as live instead of using it as delegate.

With pjax, which uses xhr in order to load elements that have no events attached to them that might be a problem.

So, my recommendation would be to use parent element which is not reloaded and attach event on it. Like this, with topmost, not reloaded element, instead of body:

$("body").on("switchImage", "#img-switcher", function(e, src){
  $(this).attr({ 'src': src });
});

$("body").on("click", "img.img-switcher", function() {
    $("#img-switcher").trigger("switchImage", $(this).attr('src'));
});

Upvotes: 2

Related Questions