history.pushState: Back button until history at "first" entry, then default back button behaviour

77 Views Asked by At

I want to build a reload-free page navigation with javascript and AJAX without a framework. Wether that is a good idea or not doesn't really matter as this project is rather for demonstration, that this is indeed possible :)

I have done it before but for the life of me can't figure out how anymore.

Ideally I want a solution that works as follows:

a function, let's call it display() for this purpose that takes a parameter called 'id'.

This id parameter will then be passed to an ajax request that delivers the content respectively and updates the URL using pushState to the new address, so for example from / to /faq where id is then 'faq'.

Then if display is called again, this time with 'browse' for id, the AJAX requests data for it and sets the URL to /browse.

Now the catch, I want the page to be able to navigate through those pages back and forward, each time triggering a new AJAX call and adjusting the URL accordingly, however if you go back to / (which would be the first element on this page), the back button should now just behave normally and allow the user to leave the page to the one that referred to it (but not use the referrer). I had a concept script for this however it "trapped" the user on my page because once history is empty the site will do nothing and the user is stuck on / or whatever was the first page.

Can someone help?

I have tried attaching a popstate listener that will only take effect if the history has elements inside but I didn't manage to get this working properly and the user was still trapped.

I managed to get page loads with data and the consequent pushState entries to happen where it will update the URL properly however the back button causes me a big headache :')

0

There are 0 best solutions below