I have 3 related questions to ask
Question 1
On a window.addEventListener('popstate', function(e)
, how do I know if the button that was pressed was the forward()
or back()
button. For example
window.addEventListener('popstate', function(e){
var buttonDirection = // the button that was clicked
if(buttonDirection == history.back()){
// blah blah blah
} else if(buttonDirection == history.forward()){
// blah blah blah
}
})
Question 2
I want to pushState
after ajax
success in order to change the page content so I did this, I don't really know if its the best way to do that
$.ajax({
url: 'path.php',
success: function(data){
$('html').html(data);
history.pushState('', '', 'path.php');
var pushed = 'yes';
}
})
Now the issue is after the ajax
success and pushed = yes
then I want to listen to the event for when the back button is clicked to retrieve the previous page content because after the history.pushState
the forward()
button is disabled, so I did this
window.addEventListener('popstate', function(e){
if(pushed == 'yes'){
// run code to restore back previous page content
$.ajax({
url: 'current_page.php',
success: function(data) {
$('html').html(data);
pushed = 'yesBack';
}
});
}
// now I want to run another code to replace the page content again if the forward button is clicked and pushed is == yesBack
// that's where my reason for question 1 come out
// so how do I know if the button that was clicked is the forward
})
Final Question
If you study Facebook on mobile browsers this is what you will observe:
- If you are on a profile picture album page and you click a photo, the
history.pushState
is fired andajax
request is used to change the page content which will now display the image you clicked. - If you click the back button the
ajax
request is used again to retrieve the previous page contents. - If you click the forward button again the
ajax
request is used again to change the page content to display the image once again. - If you continue to now scroll through the images by clicking the next or previous links and the
history.pushState
is fired again and theajax
request is used to retrieve the new image, no matter how much images you have scrolled, if you click the back button again it takes you back to the first page which is the profile picture album page. - If you then click the forward button again, it takes you to the page you left off before clicking the back button.
Now my third question is how can I achieve all these observations also in my own web page.
I tried viewing the Facebook source code but I couldn't understand it or find anywhere the history.pushState
is triggered. Please do anyone have an answer to any of my listed questions or a document I can read to get an answer