I have a one page website, example.com. There are two sections: intro at the top of the page, and contact at the bottom of the page. If I want someone to visit the contact section without having to scroll through the intro, I give them this link: example.com/#contact. I'm talking about these visits below.
The browser automatically scrolls down to the contact section, but it ignores the fixed navigation at the top of the page, so the contact section is scrolled behind the navigation so the top of the contact section becomes invisible. This is what I want to correct using JavaScript, by subtracting the height of the fixed navigation from the scroll position. Let's call this function the scrollCorrector
. The problem is that I don't know exactly when such an automatic scrolling happens, so the scrollCorrector
isn't called everytime it should be.
When should the scrollCorrector
be called? When the automatic scrolling happens because of the hash portion. Why not to use onscroll
? Because this way I can't differenciate an auto scroll from a user scroll. Why not to use onclick
on every <a href="example.com/#contact">
? I'll use it, but what if a user navigates by the browser's back button? Okay, I'll use onpopstate
as well. But what if the user comes from example.com/#intro by manually rewriting the URL to example.com/#contact? Okay, I'll use onhashchange
as well. But what if the user is already on example.com/#contact, clicks to the address bar, and presses enter without any modification? None of the above helps then.
What event should I listen to then? If such an event doesn't exist, how could the scrollCorrector
know that an automatic scroll has just happened?