Skip to content

Instantly share code, notes, and snippets.

@majido
Created May 6, 2019 16:21
Show Gist options
  • Save majido/f0e95ed018a3e749d99e32dc99147c07 to your computer and use it in GitHub Desktop.
Save majido/f0e95ed018a3e749d99e32dc99147c07 to your computer and use it in GitHub Desktop.
Reliable feature detection for scroll-snap-stop
// Chrome inadvertantly shipped scroll-snap-stop in Chrome 69 but the feature was implemented in Chrome v75.
// This means that the normal css feature detection CSS.supports('scroll-snap-stop: always)' does not work
// in Chrome between v69 - v75.
// Below is an alternate way of feature detecting scroll-snap-stop that uses a temporary hidden scroller.
const scroller = document.createElement('div');
scroller.style = "opacity:1; position:relative; width: 40px; height: 40px; overflow: scroll; scroll-snap-type: x mandatory;";
const snap1 = document.createElement('div');
snap1.style="margin-left: 0px; width: 1px; height: 1px; scroll-snap-align: start; background-color: blue;"
// Only the middle one traps snapping via scroll-snap-stop: always
const snap2 = document.createElement('div');
snap2.style="margin-left:10px; width: 1px; height: 1px; scroll-snap-align: start; scroll-snap-stop: always; background-color: blue;"
const snap3 = document.createElement('div');
snap3.style="margin-left:100px; width: 1px; height: 1px; scroll-snap-align: start;"
scroller.append(snap1, snap2, snap3);
document.body.appendChild(scroller);
// Use scrollBy since per spec scrollBy is directional scroll and should honor scroll-snap-stop.
scroller.scrollBy({left: 100});
// Allow one pixel deviation to take into account sub-pixel scrolling.
const is_snap_stop_supported =
Math.abs(scroller.scrollLeft - snap2.offsetLeft) < 1;
console.log('scroll-snap-stop is ' + (is_snap_stop_supported? '' :'NOT' )+ ' supported')
scroller.remove()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment