Reputation: 43
I'm creating a website where I'd liked to transition between pages seamlessly (like an app). To do that I've settled on ajax-ing the content I need from the requested page with a preloader in between as a transistion. I have the following code:
var url = "";
var historyUrl = "";
$('a').on('click', function(e){
url = $(this).attr("href");
historyUrl = window.location.pathname;
e.preventDefault();
$('#wrap main').removeClass('active');
$("#wrap main").load(url + " #wrap main", function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
setTimeout(function() {
$('#wrap main').addClass('active');
}, 1000);
history.pushState(null, null, url);
}
if (textStatus == "error") {
// Error out
}
});
e.stopPropagation();
});
$(window).on('popstate', function(){
$('#wrap main').removeClass('active');
$("#wrap main").load(historyUrl + " #wrap main", function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
setTimeout(function() {
$('#wrap main').addClass('active');
}, 1000);
}
if (textStatus == "error") {
// Error out
}
});
});
As you can see I'm triggering on all a tags in order to test this out. This code works fine for the most part. If I go to the first page and click a link I successfully transition to the second page without the browser reloading. The URL changes and the history is pushed. If I then click the back button I will end up back on the first page successfully too.
The problem occurs thereafter; if I then proceed to click the same link I clicked on the first page the first time, it will ignore the on click function and just load the second page as a standard browser would.
i can't figure out why this would happen. I think it's something to do with the pushState but I can't quite put my finger on it.
Am I missing something obvious here?
Thanks
Upvotes: 0
Views: 84
Reputation: 10879
When you dynamically load content, events are not automagically bound to elements. That's why after dynamically changing back to the first page, there is no event handler for the click on the link.
Change
$('a').on('click', function(e){
to
$(document).on('click', 'a', function(e){
and it should work.
This defers the click event to the document (which is not changing) and executes the callback function if the selector in the second argument ('a'
) matches the event target.
Upvotes: 1