Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

swiffy-slider

Package Overview
Dependencies
Maintainers
2
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swiffy-slider

Swiffy slider is a touch enabled super lightweight html slider and carousel using browser scroll, css grid and scroll snap align and less than 1.5 kb javascript. Comes in css mode only version

  • 1.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
436
decreased by-60.22%
Maintainers
2
Weekly downloads
 
Created
Source

Swiffy Slider Logo

Swiffy Slider

Super fast carousel and slider with touch for optimized websites running in modern browsers.
Explore Swiffy Slider docs »

See examples · Visual carousel and slider configuration

version npm version CSS gzip size CSS Brotli size JS gzip size JS Brotli size

Swiffy Slider

Super fast carousel and slider with touch for optimized websites running in modern browsers.

Modern browser offers really good options these days to create much better user experience for sliders and carousels than existing libraries offer.

This project utilizes what is available in modern browsers resulting in a super lightweight and fast slider, greatly reducing the javascript footprint and increase performance to meet todays standards.

  • Uses native browser scroll behavior, scroll-snap and CSS grid to provide the best mobile and touch experience
  • Can run in CSS only mode - no js for even better performance
  • SEO friendly - all content is in pure markup
  • WCAG friendly - all content is in pure markup and can be annotated accordingly, supports tabbing, keyboard navigation, aria attributing and all what is needed.
  • Navigate with Touch, Keyboard, trackpad, pen and Mouse - because it is just browser scrolling
  • Setup is done in pure markup and css classes, no scripting required
  • No js loading of slides, configuration or initialization
  • Vanilla javascript, less than 1.3kb ~110 lines
  • Very low overall footprint ~4.5kb in total (css+js gzip'ed)

Table of contents

Quick start

1. Add CSS and JS to website head section
<script src="https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.min.js" defer>
<link href="https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/css/swiffy-slider.min.css" rel="stylesheet">
2. Add markup
<div class="swiffy-slider slider-item-helper">
    <ul class="slider-container">
        <li>Slide 1</li>
        <li>Slide 2</li>
        <li>Slide 3</li>
    </ul>

    <button type="button" class="slider-nav"></button>
    <button type="button" class="slider-nav slider-nav-next"></button>

    <div class="slider-indicators">
        <button class="active"></button>
        <button></button>
        <button></button>
    </div>
</div>

Swiffy Slider script automatically binds to all .swiffy-slider instances

Additional installation options

  • Download the latest release
  • Clone the repo: git clone https://github.com/dynamicweb/swiffy-slider.git
  • Install with npm: npm install swiffy-slider
  • Install with yarn: yarn add swiffy-slider

Read the Getting started page for examples, configuration options and a visual configurator.

Features

  • Carousel - Slide any content. Images, cards, videos, text, banners, posters, anything markup
  • Carousel - Slide using touch, keyboard, mouse or navigation buttons
  • Carousel - 1, 2, 3, 4, 5 or 6 slides visible in the slider wrapper
  • Carousel - snap to start or center slide items
  • Carousel - Slide one item or entire page on navigate when showing more than one
  • Carousel - Partially reveal next and previous (optional) slide to indicate touch scroll is available
  • Carousel - Loop to start when slides end
  • Navigation - 7 built in navigation styles for next and previous navigation in light or dark mode, 14 in total
  • Navigation - Overlay or outside navigation options
  • Navigation - Show navigation arrows on hover or always. Show on desktop, but not touch
  • Indicators - 3 built in indicator styles; pin, dots or squares in light or dark mode
  • Indicators - Overlay or outside location of indicators
  • Indicators - Navigate to slide by clicking indicator
  • Auto play - Automatically slide with specified interval
  • Auto pause - Stop playing when mouse is hovering carousel or touch is used
  • Scripting - Automatic or manual initialization of slider instances using swiffyslider.init or swiffyslider.initSlider
  • Scripting - Execute scripts when an item is done sliding using swiffyslider.onSlideEnd
  • Scripting - Start and stop automatic sliding using script

What's included

Within the download you'll find the following directories and files. You'll see something like this:

swiffy-slider/
├── dist/
│   ├── css/
│   │   ├── swiffy-slider.min.css
│   │   ├── swiffy-slider.min.css.map
│   ├── js/
│   │   ├── swiffy-slider.ESM.min.js
│   │   ├── swiffy-slider.ESM.min.js.map
│   │   ├── swiffy-slider.min.js
│   │   ├── swiffy-slider.min.js.map

The download contains compiled and minified CSS and JS (swiffy-slider.min.*). source maps (swiffy-slider.*.map) are available for use with certain browsers' developer tools.

Bugs and feature requests

Have a bug or a feature request? Check out the issues section and see if your issue or idea is already created. If your problem or idea is not addressed yet, please open a new issue.

Documentation

Swiffy slider documentation website is part of this repo and can be found in the docs folder. Visit the doc on our github documentation page

Markup structure

The slider markup is a .swiffy-slider wrapper that has 3 sections.

  • One .slider-container that contains the slides
  • Two .slider-nav buttons that is navigation buttons previous and next (optional)
  • One .slider-indicators that contains the indicators (optional)
<div class="swiffy-slider [slider options] [navigation options] [indicator options]" data-slider-nav-autoplay-interval="3000">
    <ul class="slider-container">
        <li>Slide 1</li>
        <li>Slide 2</li>
    </ul>

    <button type="button" class="slider-nav"></button>
    <button type="button" class="slider-nav slider-nav-next"></button>
    
    <div class="slider-indicators">
        <button class="active"></button>
        <button></button>                
    </div>    
</div>

This example uses ul>li for slides. Can also be i.e. div or other elements. This example uses button for navigation. Could also be divs, but cannot be ul>li as that would be nested. This example uses div>button for indicators but could be other elements, i.e. ul>li structure instead. Wether to use buttons or div for the navigating elements, depends on how WCAG needs to be handled.

Options

Slider wrapper

Change behavior and styles on slides, navigation and indicators by adding option css classes to the .swiffy-slider wrapper.

CSS class
_______________________________
Description
_______________________________
swiffy-sliderThe overall wrapper of the slider instance. Should be a block element. Can contain 3 different things as direct children; slider-container, slider-indicators and slider-nav
Slider sections

For possible child elements to the swiffy-slider wrapper. These sections adds slides, navigation and indicators

CSS class
_______________________________
Description
_______________________________
slider-container
  • Creates the scrollable container that holds the slides
  • Can be any element and is a CSS grid
  • Using a ul>li structure for the container and slides provides good semantics
  • The direct descendants of this element are the slides them selves and can hold any markup
  • The width of the slides are controlled by the slider options. Default is 100% width
  • Can be styled using slider-item-* options
slider-nav
slider-nav-next
  • Creates a navigation button
  • Should be button element and there should be exactly 2
  • Default is a left button
  • Add slider-nav-next to make the next button
  • Can be styled using slider-nav-* options
slider-indicators
  • Creates a container for indicator buttons
  • The direct descendants of this element are the indicators. Add active for the active indicator for first load
  • Descendants should be button elements and there should be one button per slide or per page when showing more than one slide
  • Can be styled using slider-indicators-* options
Slider options

For the swiffy-slider wrapper. The slider-item-* option classes affects the slides (The slider-container children)

CSS class
_______________________________
Description
_______________________________
slider-item-show2
slider-item-show3
slider-item-show4
slider-item-show5
slider-item-show6
Shows 2, 3, 4, 5 or 6 slides at a time in the slider wrapper. Each slide is either 1/2, 1/3, 1/4, 1/5 or 1/6 of the slider wrapper width.
slider-item-revealReveals some of previous and next slide. Each slide is either 1/1, 1/2, 1/3, 1/4 or 1/6 of the slider wrapper width minus a little to reveal next and previous slides
slider-item-ratioEnables ratio sizing of the slide elements. Default ratio is 2:1 or 50% meaning the slides have half the heigh of their width. This option sets object-fit:cover; on first element inside the slide element - to stretch images to fill out the slide box and keep aspect ratio.
slider-item-ratio-32x9
slider-item-ratio-21x9
slider-item-ratio-2x1
slider-item-ratio-16x9
slider-item-ratio-4x3
slider-item-ratio-1x1
slider-item-ratio-3x4
Controls the slide ratio when ratio is enabled. Default ratio is 2:1 or 50% meaning the slides have half the heigh of their widt.
slider-item-ratio-containSets the content of a ratio enabled slide to have object-fit:contain; instead of default object-fit:cover;. This ensures that if the content of the slide is an image or embedded video, it is scaled down so all is visible within the slide box.
slider-item-nogapRemoves the horisontal gap between slides
slider-item-snapstartSnaps slides to start of the slider wrapper instead of center when using .slider-item-reveal
slider-item-nosnapRemoves auto snapping for slides so they slide freely. Primarily have an affect on touch devices as navigating with arrows and indicators is per slide or per page
slider-item-nosnap-touchSame effect as slider-item-nosnap but only on devices that has a primary input which is not a mouse, i.e. mobile media (hover: none)
slider-item-shadowAdds a dark shadow to both sides of the slider wrapper
slider-item-helperFor debugging: Adds a test layout to slide items; minimum height, background color, centers content and background. Meant for testing and should be removed in real code
Navigation options

For the swiffy-slider wrapper. The slider-nav-* option classes affects the slider-nav elements

CSS class
_______________________________
Description
_______________________________
slider-nav-pageSlides entire page when showing more than one slide item on the slider wrapper. Default behavior moves just one slide to the left or right
slider-nav-noloopDisables slider loop - so when on last slide navigate next does not take the user to the first slide
slider-nav-nodelayDisables smooth scrolling when sliding using navigation buttons, indicators and autoplay. Makes the new slide or page appear instantly with no scroll animation. Does not affect touch navigation
slider-nav-autoplayAutomatically slide to next slide or next page in intervals. Default is 2500 ms = 2.5s
data-slider-nav-autoplay-interval attributeChanges the default autoplay interval - value is in ms. data-slider-nav-autoplay-interval="3000". Default value is 2500, minimum value is 750 ms
slider-nav-autopauseStops and restarts the autoplay when mouse is hovering the slider wrapper or when it is touched on touch devices. Will restart on mouseout, but not when touch ends
slider-nav-roundChanges the default navigation arrows to a circle with arrow. Default color is white with black arrow
slider-nav-touchShows navigation buttons on touch devices. By default navigation buttons are hidden on touch devices using the media (hover: none) query. By adding this option, the navigation buttons are always visible on touch devices
slider-nav-visibleMakes the nav buttons visible always. By default navigation buttons are hidden until the slider wrapper is hovered
slider-nav-outsideMoves the navigation buttons outside the slider wrapper and shrinks the width of the slider wrapper accordingly (by 3 or 5 rem on each side depending on navigation style)
slider-nav-outside-expandMoves the navigation buttons outside the slider wrapper by applying negative margins (-3 or -5 rem) so the slides and wrapper keeps their size. The navigation buttons overlays surrounding content.
slider-nav-scrollbarMakes the scrollbar for the .slider-container visible. Acts as indicator and navigation if running in css only mode. On touch devices the scrollbar is not shown when not sliding because that is how the browser behaves
slider-nav-darkChanges the navigation buttons to a dark version. Black arrows or black circle with white arrows
Indicator options

For the swiffy-slider wrapper. The slider-indicators-* option classes affects the slider-indicators child elements

CSS class
_______________________________
Description
_______________________________
slider-indicators-roundChanges the default indicators to a circle
slider-indicators-squareChanges the default indicators to a square
slider-indicators-outsideMoves the indicator buttons under the slider wrapper and increases the height of the slider wrapper but not the slides them selves
slider-indicators-darkChanges the indicator buttons to a dark version
slider-indicators-highlightHightlights the active indicator even more by increasing its size
slider-indicators-smShows indicator buttons on small devices under 992px in width. By default indicator buttons are hidden on small devices. By adding this option, the indicators buttons are always visible. Since the number of indicators and number of slides does not match on small devices when showing more than one item per page, do not use this option in that case

Javascript

The Swiffy Slider script can be accessed using window.swiffyslider or simply swiffyslider

All options and behavior is handled by the css classes, so using the scripts directly is only for more advanced scenarios.

Method
_______________________________
Description
_______________________________
swiffyslider.version;Needs no explanation :-)
swiffyslider.init(rootElement = document.body);Initializes all instances of .swiffy-slider elements and binds events to handle navigation, indicators and autoplay. By default document.body is searched for instances, but can be limited further to i.e. content area (and skip header, navigation, footer etc) to further improve init performance.
swiffyslider.initSlider(sliderElement);Initializes one instance of swiffy slider wrapper. The passed element has to be a .swiffy-slider element
swiffyslider.slide(sliderElement, next = true);Slides to the next slide or next page depending on the nav settings. The passed slider element has to be a .swiffy-slider element. By default this method slides next, but call it with false to slide to previous
swiffyslider.slideToByIndicator();This method is called when an indicator button is clicked. Should not be called directly. Instead call slideTo
swiffyslider.slideTo(sliderElement, slideIndex);Slides to the specified slide (index starts with 0 for first slide). The passed slider element has to be a .swiffy-slider element.
swiffyslider.onSlideEnd(sliderElement, delegate, timeout = 125);Provide a callback/delegate function to get called when sliding ends. The default timeout is 125ms and should not be too low as it could cause the delegate to be called more than once on each scroll. The passed slider element has to be a .swiffy-slider element.
swiffyslider.autoPlay(sliderElement, timeout, autopause);Manually starts autoplay for a container using the specified timeout. Autopause can be enabled. Usually auto play is handled using css option classes. This method can be used to start autoplay when the slider scrolls into view or similar. The passed slider element has to be a .swiffy-slider element.
swiffyslider.handleIndicators(sliderElement);Manually updates the indicators active state to reflect the current position of the slider. The passed slider element has to be a .swiffy-slider element.

Listening for sliding ends for a container

<script>
const sliderElement = document.getElementById('myslider');
swiffyslider.onSlideEnd(sliderElement, function() {
    console.log('Scrolling stopped');
});
</script>

Listening for sliding ends for a container and find visible slides

<script>
window.addEventListener(&#39;load&#39;, () =&gt; {
    const sliderElement = document.getElementById(&#39;myslider&#39;);
    swiffyslider.onSlideEnd(sliderElement, function() {
        const visibleSlideElements = getVisibleSlides(sliderElement);
        const visible = [];
        for (const slide of visibleSlideElements) {
            visible.push(slide.innerText);
        }
        console.log(visible);
        console.log(visibleSlideElements);
    });
});

function getVisibleSlides(sliderElement) {
    const container = sliderElement.querySelector('.slider-container');
    //returns an array of slide elements that are fully or partially visible
    const visibleSlides = [];
    //We are using a grid layout and the slides left and right properties include the width of the gap, so when comparing with container width add a gap for each side of the slide gap.
    const gapWidth = parseInt(window.getComputedStyle(container).columnGap);
    for (const slide of container.children) {
        var slideScrollLeftPosition = slide.getBoundingClientRect().left - container.getBoundingClientRect().left;
        var slideScrollRightPosition = slideScrollLeftPosition + slide.offsetWidth - gapWidth;
        if (slideScrollLeftPosition &gt;= 0 &amp;&amp; slideScrollRightPosition &lt;= container.offsetWidth) {
            visibleSlides.push(slide);
        }
    }
    return visibleSlides;
}
</script>

Javascript loading and binding

Avoid autobinding by adding data-noinit attribute on the script tag and then attach the slider manually

<script src="https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.min.js" data-noinit defer>
<script>
    window.addEventListener('load', () => {
        //Use only one of the loading options below!
        //loads all sliders
        swiffyslider.init();
        //loads specific slider
        swiffyslider.initSlider(document.getElementById('myslider'));
    });
</script>
<div class="swiffy-slider" id="myslider">
  <div class="slider-container">
    <div></div>
  </div>
  ...
</div>
<script src="https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.min.js" data-noinit defer>
<script>
    window.addEventListener('load', () => {
        //loads all sliders in main and skip header and footer search for increased init performance.
        swiffyslider.init(document.getElementById('content'));
    });
</script>
<header>...</header>
<main id="content">
  <div class="swiffy-slider" id="myslider">
    <div class="slider-container">
      <div></div>
    </div>
    ...
  </div>
</main>
<footer>...</footer>

Load as module using ES version of the script

<script type="module">
    import {swiffyslider} from 'https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.ESM.min.js'; 
    window.swiffyslider = swiffyslider; 
    window.swiffyslider.init(); 
</script>

Load as ES module on demand, here using load - could be when slider scrolls into view or navigation arrow is clicked the first time. Load module and initialize sliders.

<script>
window.addEventListener("load", () => {
    import ('https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.ESM.min.js').then((swiffysliderModule) => {
        swiffysliderModule.swiffyslider.init();
    });
});
</script>

Load as ES module on demand. Load module and assign to window for later script manipulation of slides

<script>
window.addEventListener("load", () => {
    import ('https://cdn.jsdelivr.net/npm/swiffy-slider@1.0.1/dist/js/swiffy-slider.ESM.min.js').then((swiffysliderModule) => {
        window.swiffyslider = swiffysliderModule.swiffyslider;
        window.swiffyslider.init();
    });
});
</script>

CSS variables

The Swiffy Slider CSS is making use of a number of CSS variables that can be overriden to control behavior and styling

Slide sizes, ratios, navigation etc. can be controlled by overruling the variable on the .swiffy-slider instance or in custom css.

VariableExampleDescription
--swiffy-slider-item-width--swiffy-slider-item-width:75%;Calculated based on the number of slides shown, the gap, reveal etc. Should not be overriden. INFO If needed, it has to be overriden on the .slider-container element.
--swiffy-slider-item-gap--swiffy-slider-item-gap:25px;Changes the gap between slides when enabled. Default --swiffy-slider-item-gap is 1rem, but can be any valid CSS mesurement. The --swiffy-slider-item-gap is part of the calculation of --swiffy-slider-item-width
--swiffy-slider-item-reveal--swiffy-slider-item-reveal:20%;Changes the width of the reveal of next and previous slides when enabled. Default --swiffy-slider-item-reveal is 8rem if previous and next is revealed and 4rem if only next is revealed (if .slider-item-snapstart is in use). The --swiffy-slider-item-reveal is part of the calculation of --swiffy-slider-item-width
--swiffy-slider-item-ratio--swiffy-slider-item-ratio:100/33.3Sets the ratio to a custom value. Use with .slider-item-ratio and omit use of any .slider-item-ratio-* classes
--swiffy-slider-item-count--swiffy-slider-item-count:8;Sets the number of slides to show - same as using .slider-item-show{n} but can i.e. be set to a number higher than 6 if needed.
--swiffy-slider-nav-light--swiffy-slider-nav-light:lightcyan;Sets the light color for navigation arrows. Default is #fff. Use to control the color of light navigation. Square and Round navigation use both colors - one for backgrond, the other for arrow color.
--swiffy-slider-nav-dark--swiffy-slider-nav-dark:darkolivegreen;Sets the dark color for navigation arrows. Default is #333. Use to control the color of dark navigation. Square and Round navigation use both colors - one for backgrond, the other for arrow color. Can be any color variable.
--swiffy-slider-nav-zoom--swiffy-slider-nav-zoom:125%;Use to overrule the navigation arrow sizes. Default is 100% for normal sizes and 75% for small sized navigation. Set to i.e. 125% to make navigation arrows larger.
--swiffy-slider-track-opacity--swiffy-slider-track-opacity:0.25;Sets the scrollbar track opacity when scrollbar is displayed
--swiffy-slider-track-height--swiffy-slider-track-height:1rem;Sets the scrollbar track height. Default is .5rem if scrollbar (.slider-nav-scrollbar) is enabled.

Example

<div class="swiffy-slider slider-item-reveal slider-item-ratio slider-nav-round slider-nav-visible" 
style="
--swiffy-slider-item-ratio:100/33.3;
--swiffy-slider-nav-light:lightcyan;
--swiffy-slider-nav-dark:darkolivegreen;
--swiffy-slider-nav-zoom:85%;
--swiffy-slider-item-reveal:25%;">

    <ul class="slider-container">
        <li>...</li>
    </ul>

    <button type="button" class="slider-nav"></button>
    <button type="button" class="slider-nav slider-nav-next"></button>

    <div class="slider-indicators">
        <button class="active"></button>
        <button></button>
        <button></button>
    </div>
</div>

Safari smooth scrolling polyfill

Sliding the carousel on touch devices using fingers are not affected by this issue.

When sliding using buttons, indicators and javascript, the new slides are shown instantly with no animation or smoothing when using Safari.

In Safari based browsers, smooth scrolling is not supported because it is still lacking browser support. See Can I use

If you want to support smoooth scrolling on Safari based browsers, add this polyfill to your head section

<script src="https://unpkg.com/smoothscroll-polyfill/dist/smoothscroll.min.js"></script>

Limitations

These limitations are known and intentionally there to keep this library small, fast and smooth.

  • Scroll speed comes in 2 flavors - instant or 'smooth'. This is because that is what browsers support out of the box using CSS scroll-behavior. See MDN
  • Does not support slides of uneven widths. The width is controlled by the width of the wrapper and can have 1-6 slides per page depending on configuration.
  • Smooth scrolling is not supported out of the box in Safari (iOS + Mac) but can be fixed using a polyfill. See polyfill
  • RTL is untested but as the entire slider is just markup, it should be supported very well
  • Works in 'modern' browsers from the last ~3 years only. No IE support or anything funny.
  • No animations are implemented except smooth scrolling

Use other sliders and carousels if these limitations is important in your project.

Contributing

You are more than welcome to contribute by opening issues and create pull requests. Keep in mind that this project is meant to be very simple in nature and support recent browsers only.

This project is not going into a race of adding as many features as possible - but quite the opposite. Performance and filesize has high priority.

The general rule is, that Swiffy Slider is covering the most common usages, and that more exotic usages are made in examples. If not at least 50% of all installations need a feature, the feature probably belong somewhere else.

Examples of more exotic use cases are more than welcome as part of the examples, so please create pulls for that.

Open tasks that you could help with:

  • Svelte component
  • Vue component
  • React component

Thank you for your understanding.

Versioning

See the Releases section of our GitHub project for changelogs for each release version of Swiffy Slider.

Creators

Nicolai Høeg Pedersen

Dynamicweb

Code and documentation copyright 2021 the Swiffy Slider Authors and Dynamicweb A/S Code released under the MIT License. Docs released under Creative Commons.

Keywords

FAQs

Package last updated on 08 Nov 2021

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc