Last active
October 5, 2015 03:15
-
-
Save dgraham/9859e63700d19d443878 to your computer and use it in GitHub Desktop.
Simulate browsers' scroll-to-anchor behavior on page load.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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