Socket
Socket
Sign inDemoInstall

scroll-snap-slider

Package Overview
Dependencies
0
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    scroll-snap-slider

Mostly CSS slider with great performance.


Version published
Weekly downloads
194
decreased by-27.88%
Maintainers
1
Install size
74.3 kB
Created
Weekly downloads
 

Readme

Source

Scroll Snap Slider

JavaScript Style Guide Maintainability Tree Shaking: Supported
npm Version Dependency Count: 0 minzipped Size

Mostly CSS slider with great performance.

demo | docs

Table of Contents

Premise

This library is an opinionated minimal implementation of a common feature across many websites. To keep it small, there are not many fancy features and there is almost no error handling.

However, with a clear API and the use of a ES6 class, it can provide a useful base for custom extensions.

What this module contains:

  • Example markup for a scroll-snap slider
  • CSS default styling for a scroll-snap slider without scrollbars
  • ES6 class to slightly enhance functionality
  • ES6 class plugins for loop, autoplay, and desktop/mouse draggable features
  • TypeScript Typings

Sizes

Here are the sizes of individual modules, using terser and gzip with default options. The size increase at bundlephobia between v2 and v3 is due to the entrypoint changing from 'ScrollSnapSlider' to 'index'.

Itemminified (terser)minified + gzipped
index348 B143 B
ScrollSnapAutoplay1479 B559 B
ScrollSnapDraggable2459 B772 B
ScrollSnapLoop1849 B615 B
ScrollSnapPlugin70 B110 B
ScrollSnapSlider2361 B809 B

Restrictions

This library only handles sliders on the X-axis.

For more "fully-featured" implementations, go to:

Installing

npm install scroll-snap-slider 

yarn add scroll-snap-slider

Usage

The class provided in this package augments a slider with a few events and methods.

Markup

You can add whatever markup inside the slides.


<ul class="scroll-snap-slider">
  <li class="scroll-snap-slide">
    <img
      alt=""
      src="https://picsum.photos/id/1011/400/300"
    />
  </li>
  <li class="scroll-snap-slide">
    <img
      alt=""
      src="https://picsum.photos/id/1018/400/300"
    />
  </li>
</ul>

CSS

@import 'scroll-snap-slider';

Additional Styles

Prevents page navigation on horizontal scrolling, i.E. on macOS. [Support tables]

.scroll-snap-slider {
    overscroll-behavior-x: none;
    overscroll-behavior-y: auto;
}

Prevents scrolling past elements in the slider: [Support tables]

.scroll-snap-slide {
    scroll-snap-stop: always;
}

JavaScript

If you do not want to add any additional behaviour, the JavaScript instance is not needed. This class dispatches several events and exposes a few methods, with which you can enhance your slider's behaviour.

Default behaviour:

import { ScrollSnapSlider } from 'scroll-snap-slider'

const element = document.querySelector('.example-slider')
const slider = new ScrollSnapSlider({ element })

slider.addEventListener('slide-start', function (event) {
  console.info(`Started sliding towards slide ${event.detail}.`)
})

slider.addEventListener('slide-pass', function (event) {
  console.info(`Passing slide ${event.detail}.`)
})

slider.addEventListener('slide-stop', function (event) {
  console.info(`Stopped sliding at slide ${event.detail}.`)
})

Advanced config:

import { ScrollSnapSlider } from 'scroll-snap-slider'

// Do not automatically attach scroll listener
const slider = new ScrollSnapSlider({
  element: document.querySelector('.example-slider'),
  scrollTimeout: 50, // Sets a shorter timeout to detect scroll end
  roundingMethod: Math.round, // Dispatch 'slide-pass' events around the center of each slide
  // roundingMethod: Math.ceil, // Dispatch 'slide-pass' events as soon as the next one is visible
  // roundingMethod: Math.floor, // Dispatch 'slide-pass' events only when the next one is fully visible
  sizingMethod (slider) {

    // with padding
    return slider.element.firstElementChild.offsetWidth

    // without padding
    // return slider.element.firstElementChild.clientWidth
  }
})

Plugins:

You can add one or multiple of the available Plugins:

  • ScrollSnapAutoplay: Automatically slides at a given interval
  • ScrollSnapLoop: Sliding past the last element shows the first without sliding to the start (and vice-versa)
  • ScrollSnapDraggable: Drag the slider with your mouse. Note: this does not affect mobile behaviour and is not necessary for touch sliding.
import { ScrollSnapSlider } from 'scroll-snap-slider/src/ScrollSnapSlider.js'
import { ScrollSnapAutoplay } from 'scroll-snap-slider/src/ScrollSnapAutoplay.js'
import { ScrollSnapLoop } from 'scroll-snap-slider/src/ScrollSnapLoop.js'

const element = document.querySelector('.example-slider')
const slider = new ScrollSnapSlider({ element }).with([
  new ScrollSnapAutoplay(1200),
  new ScrollSnapLoop
])

Creating your own plugin:

export class CustomPlugin extends ScrollSnapPlugin {

  /**
   * Pass any config here
   * @param {*} config
   */
  constructor (config) {
    super()

    this.config = config
  }

  /**
   * Chose a unique plugin name. If you need multiple instances of the same plugin on a slider, each must return a unique id.
   * @return {String}
   */
  get id () {
    return 'lubba-wubba-dub-dub'
  }

  /**
   * Attach listeners, fetch DOM things, save reference to the slider
   * @param {ScrollSnapSlider} slider
   * @override
   */
  enable (slider) {
    // TODO method stub
  }

  /**
   * Free resources, remove listeners, ...
   * @override
   */
  disable () {
    // TODO method stub
  }
}

API

MethodDescription
slideTo(index: Number): voidScrolls to slide at index.
addEventListener(...)This is a shortcut for slider.element.addEventListener(...).
removeEventListener(...)This is a shortcut for slider.element.removeEventListener(...).
attachEventListeners()Enables the JS behaviour of this plugin. This is called in the constructor.
detachEventListeners()Disables the JS behaviour of this plugin.
destroy()Free resources and listeners. You can/should do slider = null after this.

Events

Events dispatched on the slider's element:

Event NameEvent Detail TypeDescription
slide-startNumberDispatched when sliding starts toward slide at event.detail.
slide-passNumberDispatched when sliding passes (crosses the threshold to) slide at event.detail. The threshold is defined/altered by the roundingMethod.
slide-stopNumberDispatched when sliding stopped at index event.detail, i.e. the last scroll event happened before scrollTimeout ms.

You can use the proxy methods addEventListener and removeEventListener to listen to them.

Public Properties

PropertyDescription
slide: Number (read only)Currently active slide.
element: Element (read only)The element passed into the constructor.
scrollTimeout: NumberTimeout delay in milliseconds used to catch the end of scroll events.
plugins: Map<String, ScrollSnapPlugin>Map of plugins enabled for this slider

Support

Check out the support tables for CSS scroll snap. Note that it's up to you to inject or add vendor specific code.

Keywords

FAQs

Last updated on 23 Feb 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc