Change browser back button behaviour for my web app?

爱⌒轻易说出口 提交于 2019-11-29 13:57:06

Use HTML anchor tags when clicking a navigation button (on your page). Thus, scrolling to where the anchor is located (top, left). This behaviour will make the browser's back and forward buttons navigate to the anchors.

Take these for example:

Code for button:

<a href="#filters">Filters &lt;</a>
<a href="#map">Map &gt;</a>

Just change the anchor of the forward and back buttons on your page as it corresponds to where the user is navigating to. This makes the browser keep track of where the user is on your page.

Even if you don't add actual anchor links to make the hash tags work, you can still use javascript's window.location.hash property to navigate the user yourself.

The idea of changing the native behavior of the back button on browser is definitely a red flag signaling something is being approached wrong, and is not really possible cross-browser.

I would handle the unload event for the browser to try and smoothly transition between states.

I agree with Gabe in that trying to change the behavior of the back button is usually a red flag; however, after reading what you're trying to do, I don't see a problem. (It might be a terminology thing – you're not really trying to change the back button's behavior, you're trying to add state to the browser history so that the back button can navigate through it.)

You'll want to use jQuery BBQ, which manages state on the URL's hash (the part after the #). Listen for the hashchange event and animate between your panels accordingly:

$(window).on('hashchange', function() {
    var page = $.bbq.getState('page');
    // animate to `page`
});

Now, you don't even have to attach event handlers to your next page button – just link it:

<a href="#page=map">Map</a>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!