Skip to content

Instantly share code, notes, and snippets.

@dinhanhthi
Created December 10, 2020 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinhanhthi/a08f2e0f77c467b5a08dcd687339a8b7 to your computer and use it in GitHub Desktop.
Save dinhanhthi/a08f2e0f77c467b5a08dcd687339a8b7 to your computer and use it in GitHub Desktop.
Anchor links hidden by fixed navigation
// anchor link fixed navigation from top
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 60);
}
}
// Captures click events of all <a> elements with href starting with #
addEventListener('click', function (e) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
if (e.target.tagName == "A" && e.target.hash.startsWith("#")) {
window.setTimeout(function () {
offsetAnchor();
}, 0);
}
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
@dinhanhthi
Copy link
Author

Update 03/10/21: This method is not good. It works only if we click on an <a> tag which starts with # in the href. In the case of either reloading the page (containg anchor link) or inside <a> containing an <svg>, for example, it won't work!

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