Skip to content

Instantly share code, notes, and snippets.

@tbtlr
Created August 23, 2011 10:34
Show Gist options
  • Save tbtlr/1164818 to your computer and use it in GitHub Desktop.
Save tbtlr/1164818 to your computer and use it in GitHub Desktop.
A simple JavaScript that lets you use your browser's back/forward buttons for in-page navigation by adding custom 'next' and 'previous' events to the window object.
/*
* Lets you use your browser's back/forward buttons for in-page navigation by
* adding custom 'next' and 'previous' events to the window object.
*
* Copyright (c) 2011 Tobias Schneider <[email protected]>
* This script is freely distributable under the terms of the MIT license.
*
* Example:
*
* window.addEventListener('next', function(){
* console.log('forward button clicked');
* }, false);
*
* window.addEventListener('previous', function(){
* console.log('back button clicked');
* }, false);
*/
if(window.history && history.pushState){ // check for history api support
window.addEventListener('load', function(){
// create history states
history.pushState(-1, null); // back state
history.pushState(0, null); // main state
history.pushState(1, null); // forward state
history.go(-1); // start in main state
this.addEventListener('popstate', function(event, state){
// check history state and fire custom events
if(state = event.state){
event = document.createEvent('Event');
event.initEvent(state > 0 ? 'next' : 'previous', true, true);
this.dispatchEvent(event);
// reset state
history.go(-state);
}
}, false);
}, false);
}
@zachleat
Copy link

Copyright 2001? Amazing foresight on pushState! :)

@tbtlr
Copy link
Author

tbtlr commented Aug 23, 2011

:P

@zachleat
Copy link

Is this intended for fun or production code? If fun, please ignore the following:

Feels like it would be weird to go to a page and have my forward button enabled even if I hadn't used the back button yet.

Copy link

ghost commented Feb 24, 2013

Its cool I have tested in modern browsers but in IE9 it has some issues its not working. Is that because we have to use attachEvent() function? please suggest.

@rajamanickamsaravananan
Copy link

It is not working in mac safari browser :(

@chtiland
Copy link

chtiland commented Mar 15, 2018

One thing you must know when using this script, is that you "loose" some data i.e. $_POST when you reload a form that has already been submitted (it should be annoying in some cases).

@ukfreetv
Copy link

Line 20 should be using an evaluation === not an assignment =

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment