Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Element
  4. scrollsnapchanging

Element: 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 theElement interface is fired on thescroll container when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.

Specifically, this event fires during a scrolling gesture, each time the user moves over potential new snap targets. For example, the user could scroll slowly by dragging their finger on a touch screen device, or hold down the mouse button on a scroll bar and move the mouse.scrollsnapchanging can therefore fire multiple times for each scrolling gesture.

However, it does not fire on all potential snap targets for a scrolling gesture that moves over multiple snap targets. Rather, it fires just for the last target that the snapping will potentially rest on.

Syntax

Use the event name in methods likeaddEventListener(), or set an event handler property.

js
addEventListener("scrollsnapchanging", (event) => { })onscrollsnapchanging = (event) => { }

Event type

ASnapEvent, which inherits from the genericEvent type.

Examples

Basic usage

Let's say we have a<main> element containing significant content that causes it to scroll:

html
<main>  <!-- Significant content --></main>

The<main> element can be turned into a scroll container that snaps to its children when scrolled using a combination of the CSSscroll-snap-type property and other properties. For example:

css
main {  width: 250px;  height: 450px;  overflow: scroll;  scroll-snap-type: block mandatory;}

The following JavaScript snippet would cause thescrollsnapchanging event to fire on the<main> element when one of its children 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.

js
scrollingElem.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

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp