Window: scrollsnapchanging event
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.
Thescrollsnapchanging event of theWindow interface is fired on thewindow when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.
This event works in much the same way as theElement interface'sscrollsnapchanging event, except that the overall HTML document has to be set as the scroll snap container (i.e.,scroll-snap-type is set on the<html> element).
In this article
Syntax
Use the event name in methods likeaddEventListener(), or set an event handler property.
addEventListener("scrollsnapchanging", (event) => { })onscrollsnapchanging = (event) => { }Event type
Examples
>Basic usage
Let's say we have a<main> element containing significant content that causes it to scroll:
<main> <!-- Significant content --></main>The<main> element can be turned into a scroll container using a combination of CSS properties, for example:
main { width: 250px; height: 450px; overflow: scroll;}We can then implement scroll snapping behavior on the scrolling content by specifying thescroll-snap-type property on the<html> element:
html { scroll-snap-type: block mandatory;}The following JavaScript snippet would cause thescrollsnapchanging event to fire on the HTML document when a child of the<main> element becomes a pending snap target. In the handler function, we set apending class on the child referenced by thesnapTargetBlock property, which could be used to style it differently when the event fires.
window.addEventListener("scrollsnapchanging", (event) => { // remove previously-set "pending" classes const pendingElems = document.querySelectorAll(".pending"); pendingElems.forEach((elem) => { elem.classList.remove("pending"); }); // Set current pending snap target class to "pending" event.snapTargetBlock.classList.add("pending");});At the start of the function, we select all elements that previously had thepending class applied and remove it, so that only the most recent pending snap target is styled.
Specifications
| Specification |
|---|
| CSS Scroll Snap Module Level 2> # scrollsnapchanging> |
Browser compatibility
See also
scrollsnapchangeeventscrollendeventSnapEvent- CSS
scroll-snap-typeproperty - CSS scroll snap module
- Using scroll snap events
- Scroll Snap Events on developer.chrome.com (2024)