I found a similar question on stackoverflow and was able to derive my solution from there. However, I am facing a slight issue with it.
In my case, I have a small fixed submenu at the top of the page. When I click on an anchor link, I want the scroll position to be adjusted after the submenu.
Here is my code snippet that mostly works:
function offsetSubmenu() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - submenuHeight);
}
}
$(window).on("hashchange", function () {
offsetSubmenu();
});
window.setTimeout(function() {
offsetSubmenu();
}, 1);
The code gets executed when the page loads and whenever the URL hash changes. It functions as expected in those scenarios. The problem arises when the hash remains unchanged. For instance, clicking on the first Hashlink, scrolling around, and then clicking on the same link again causes the browser to jump to the anchor without accounting for the submenu offset.
Using a click listener like $("a").click(..)
does not work because it executes before the browser navigates to the anchor element.
Does anyone have any suggestions on how to handle the offset for anchors when the URL hash remains the same?