Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event that fires when a browser scrolls to a named anchor?

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.

like image 523
andyg1 Avatar asked Oct 10 '13 14:10

andyg1


People also ask

Is scroll an event?

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.

Does scroll event bubble?

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.

How do you make a scroll anchor?

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!

How do you know if scroll is up or down?

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.


2 Answers

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.

like image 128
Joseph Avatar answered Sep 25 '22 01:09

Joseph


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.

like image 30
corrin_m Avatar answered Sep 25 '22 01:09

corrin_m