0

This is a single page website with navigation consisting of anchor links to different sections of the page. When the navigation is clicked URL updates to ex.(.com/#photos) and makes the browser add as a new page for each anchor link clicked. This makes the user have to click back multiple times if they wanted to get back to a previous website. I would like to have at max 2 back button presses, 1 to go to top of the page, 2 to go to previous website. I am really at a loss on where to implement this code, or if it is even ideal to mess with how the browser acts to the user. My google-fu turned up very little information on this issue.

1 Answers1

0

You can attach a function to window.onpopstate event and then check if window.history.length has changed. If it has not changed, probably it is the back button press.

Like this..

var prevHistoryLength = -1;
window.onpopstate = function(e){
    if (prevHistoryLength == window.history.length)
        document.location = document.referrer;
    prevHistoryLength = window.history.length;
}
vishva8kumara
  • 353
  • 1
  • 3
  • 15
  • That didn't really work. Maybe a better solution would be to prevent the URL from rewriting like www.whatever.com/index and leave it like that when anchor links are used? – Nick Smith Apr 25 '17 at 21:34