I need an event for when the user clicks on the browser back and forward buttons. I have this piece of code that works, however it executes regardless of which button I click (backward & forward). How can I handle the backward and forward button clicks separately?
The code:
if ( window.history && window.history.pushState ) {
window.history.pushState( 'forward', null, './#forward' );
$( window ).on( 'popstate', function() {
alert( 'Hello back/forward button!' );
} );
}
Is it also possible to hide the #forward
string from the URL?
Use the direction:
$(window).on('navigate', function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.