When linking to a page using a named anchor e.g. page.html#heading the browser will load the page, then jump down to the anchor. Is there a browser event that fires when this has completed?
To explain my reasons behind it: I want to use the event to trigger an animation in the browser.
Many thanks.
The scroll event fires when you scroll a webpage or an element. For a page, the scrollX and scrollY properties return the number of pixels that the document is currently scrolled horizontally and vertically.
The scroll event does not bubble up. Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.
The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection . This CSS method works great for me and is super elegant!
If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards. Update the current scroll position to the variable.
Changing the hash triggers the hashchange
event.
However, I don't think it fires when loading a url where the link already has the hash set. But you can check the hash (location.hash
) on page load if you want a certain script to run depending on the hash.
In Safari 7.0.3 on the Mac this works...
HTML has:
<a id="jumper" href="#aa">Jump</a>
JS:
<script>
var j = document.getElementById("jumper");
j.addEventListener("click", registerAnchorJump);
function registerAnchorJump(e) {
window.addEventListener("scroll", unregisterAnchorJump);
}
function unregisterAnchorJump(e) {
// trigger your animation...
console.log(window.scrollY);
window.removeEventListener("scroll",unregisterAnchorJump);
}
</script>
Fancy footwork to prevent constant firing of scroll event as user scrolls window normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With