Skip to content

Instantly share code, notes, and snippets.

@dgraham
Last active October 5, 2015 03:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgraham/9859e63700d19d443878 to your computer and use it in GitHub Desktop.
Save dgraham/9859e63700d19d443878 to your computer and use it in GitHub Desktop.
Simulate browsers' scroll-to-anchor behavior on page load.
(function() {
function hashchange() {
if (!location.hash) {
return;
}
// Don't do anything if the current target exists.
if (document.querySelector(":target")) {
return;
}
var name = "user-content-" + decodeURIComponent(location.hash.slice(1));
var target = document.getElementById(name) || document.getElementsByName(name)[0];
if (target != null) {
target.scrollIntoView();
}
}
// Scroll to anchor when clicked on page.
window.addEventListener('hashchange', function() {
hashchange();
});
// Scroll to anchor on page load.
$(function() {
hashchange();
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment