Skip to content

Instantly share code, notes, and snippets.

@schjetne
Created April 24, 2013 12:12
Show Gist options
  • Save schjetne/5451674 to your computer and use it in GitHub Desktop.
Save schjetne/5451674 to your computer and use it in GitHub Desktop.
Code to navigate to previous page in history if it exists, otherwise go back to a default "back" location.
// Use: ><a href="list.html" class="js-back">Go back</a>
$('.js-back').on('click', function(evt) {
if (document.referrer != "") {
evt.preventDefault();
history.back();
}
});
@schjetne
Copy link
Author

Todo: Timeout to check if history.back() actually runs
Todo: Only run history.back() if referrer is on same domain

@Pistil-Studio
Copy link

Pistil-Studio commented Apr 25, 2017

For your second @todo : Only run history.back() if referrer is on same domain

$('.js-back').on('click', function(evt) { if (document.referrer.indexOf(window.location.host) !== -1){ evt.preventDefault(); history.back(); } });

@paramir
Copy link

paramir commented Sep 3, 2019

@Pistil-Studio - Thank you! Works perfect :)

@Hoodgail
Copy link

Hoodgail commented Jan 8, 2020

//testing
console.log('test')

@namnguyen2091
Copy link

first solution doesn't work, @Pistil-Studio may be ok

@johnmugabe
Copy link

Thanks @Pistil-Studio. Works perfectly

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