erol_smsr erol_smsr - 1 year ago 148
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download