scroll snap in javascript

To implement scroll snapping in JavaScript, we can use the scroll-snap-type and scroll-snap-align CSS properties together.

Here's an example code snippet:

<style>
  /* Set the container to snap scroll */
  .container {
    scroll-snap-type: y proximity;
    overflow-y: scroll;
    height: 300px;
  }
  /* Set each item to snap */
  .item {
    scroll-snap-align: start;
    height: 300px;
  }
</style>

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
  <div class="item">Item 4</div>
  <div class="item">Item 5</div>
</div>

<script>
  // Optional: Use smooth scrolling
  document.querySelector('.container').addEventListener('wheel', event => {
    if (event.deltaY > 0) {
      event.target.scrollBy({
        top: 300,
        behavior: 'smooth'
      });
    } else {
      event.target.scrollBy({
        top: -300,
        behavior: 'smooth'
      });
    }
    event.preventDefault();
  });
</script>
829 chars
40 lines

In this example, we first set the container to scroll snap vertically using y proximity as the value for scroll-snap-type. We also set the height of the container to 300px and enable overflow-y: scroll to enable vertical scrolling.

Then, we set the scroll-snap-align property of each item to start to make each item snap to the top of the container when scrolled.

Optionally, we can use smooth scrolling by registering the wheel event listener to the container and calling the scrollBy() method to scroll by 300px top or bottom depending on the direction of the scroll wheel.

Note that scroll snapping is not supported by all browsers yet, so it's important to add vendor prefixes and fallbacks if necessary.

gistlibby LogSnag