When you have a hash link on your page ( href=”#target” ) sometimes the browser scrolls too low and cuts off or puts too close to the top the target element.
You can offset this hash link by hooking into the ‘hashchange’ event.
1 2 3 4 5 |
// Allow a hash link to move X pixels above the target location // https://stackoverflow.com/questions/17534661/make-anchor-link-go-some-pixels-above-where-its-linked-to window.addEventListener("hashchange", function () { window.scrollTo(window.scrollX, window.scrollY - 100); }); |
This does NOT resolve linking directly to this hash tag, but will fix the on page hash link.
To do that you can setup the following functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// The function actually applying the offset function offsetAnchor() { if (location.hash.length !== 0) { window.scrollTo(window.scrollX, window.scrollY - 100); } } // Captures click events of all <a> elements with href starting with # $(document).on('click', 'a[href^="#"]', function(event) { // Click events are captured before hashchanges. Timeout // causes offsetAnchor to be called after the page jump. window.setTimeout(function() { offsetAnchor(); }, 0); }); // Set the offset when entering page with hash present in the url window.setTimeout(offsetAnchor, 0); |
Thanks to Eric Olsen over at stack overflow!