erol_smsr erol_smsr - 5 months ago 59
Javascript Question

Javascript History.pushState forward and backward history

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
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