Created
December 10, 2020 10:56
-
-
Save dinhanhthi/a08f2e0f77c467b5a08dcd687339a8b7 to your computer and use it in GitHub Desktop.
Anchor links hidden by fixed navigation
This file contains 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update 03/10/21: This method is not good. It works only if we click on an
<a>
tag which starts with#
in thehref
. In the case of either reloading the page (containg anchor link) or inside<a>
containing an<svg>
, for example, it won't work!