Tiny Slider

repository·master·Indexed 26 days ago

https://github.com/ganlanyuan/tiny-slider

A lightweight, flexible vanilla JavaScript slider and carousel library inspired by Owl Carousel. Version 2.9.4 supports features such as loop, autoplay, responsive layouts, lazy loading, and custom events. It provides the tns() function for initialization and a TinySliderInstance object for programmatic control via methods like goTo(), play(), pause(), and destroy().

Tokens
6.4K
Snippets
8
Records
19
Agent score
40%

What's inside tiny-slider

  1. Quickstart: Use Tiny Slider 2 in your project

    master

    To use Tiny Slider 2, follow these three steps:

    1. Add CSS: Include the tiny-slider.css file. If you need to support IE8, include the IE8 polyfill.
    2. Add markup: Create a container element (e.g., a div or ul) with child elements representing the slides.
    3. Initialize the slider: Call the tns() function. You can include the script via a CDN, import it via a bundler like Webpack/Rollup, or use an ES module import.
    <!-- 1. Add CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.4/tiny-slider.css">
    <!--[if (lt IE 9)]><script src="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.4/min/tiny-slider.helper.ie8.js"></script><![endif]-->
    
    <!-- 2. Add markup -->
    <div class="my-slider">
      <div>Slide 1</div>
      <div>Slide 2</div>
      <div>Slide 3</div>
    </div>
    
    <!-- 3. Call tns() using ES Modules -->
    <script type="module">
      import {tns} from './src/tiny-slider.js';
    
      var slider = tns({
        container: '.my-slider',
        items: 3,
        slideBy: 'page',
        autoplay: true
      });
    </script>
  2. Initialize Tiny Slider with dynamic content

    master
    Tiny Slider works with static content in the browser. If you are loading your HTML content dynamically (e.g., via AJAX or a frontend framework), you must ensure that tns() is called only after the new HTML has been fully loaded into the DOM.
  3. Configure responsive breakpoints

    master

    You can redefine specific options for different viewport widths using the responsive object. Breakpoints behave like (min-width: breakpoint) in CSS, meaning an undefined option at a higher breakpoint will be inherited from the previous smaller breakpoint.

    Supported responsive options: startIndex, items, slideBy, speed, autoHeight, fixedWidth, edgePadding, gutter, center, controls, controlsText, nav, autoplay, autoplayHoverPause, autoplayResetOnVisibility, autoplayText, autoplayTimeout, touch, mouseDrag, arrowKeys, disable.

    Note: fixedWidth can only be changed to other positive integers; it cannot be changed to 0, negative integers, or other data types.

    var slider = tns({
      container: '.my-slider',
      items: 1,
      responsive: {
        640: {
          edgePadding: 20,
          gutter: 20,
          items: 2
        },
        700: {
          gutter: 30
        },
        900: {
          items: 3
        }
      }
    });
  4. Implement lazyloading in Tiny Slider

    master

    To enable lazyloading, set the lazyload option to true.

    Requirements:

    1. Add the CSS class .tns-lazy-img to every image you want to lazyload (unless lazyloadSelector is specified).
    2. Use the data-src attribute to hold the real image source instead of src.
    3. If using autoWidth, every image must have a width attribute.

    Options:

    • lazyload: Boolean (Default: false).
    • lazyloadSelector: String (Default: '.tns-lazy-img').
  5. Implement a CSS fallback for no-JS environments

    master

    If JavaScript is disabled, you can provide a basic CSS fallback to ensure the slider content remains accessible and scrollable.

    .no-js .your-slider { overflow-x: auto; }
    .no-js .your-slider > div { float: none; }
  6. Get slider information with getInfo()

    master

    The getInfo() method returns a detailed object containing the current state and DOM elements of the slider. This is useful for manual UI updates or tracking the current index.

    Returned Object Properties:

    • container: The slider container element.
    • slideItems: List of slide elements.
    • navContainer: The navigation container element.
    • navItems: The dots/navigation list.
    • controlsContainer: The controls container element.
    • hasControls: Boolean indicating if controls exist.
    • prevButton / nextButton: The previous and next button elements.
    • items: Number of items on a page.
    • slideBy: Number of items to slide by.
    • cloneCount: Number of cloned slides.
    • slideCount: Original slide count.
    • slideCountNew: Total slide count after initialization.
    • index: Current index.
    • indexCached: Previous index.
    • displayIndex: Current display index (starts from 1).
    • navCurrent: Current dot index.
    • navCurrentCached: Previous dot index.
    • pages: Visible navigation indexes.
    • pagesCached: Previous visible navigation indexes.
    • sheet: The sheet object.
    • event: The event object (if available).
  7. Subscribe to custom slider events

    master

    You can listen to slider lifecycle and interaction events using the slider.events object.

    Available Events: indexChanged, transitionStart, transitionEnd, newBreakpointStart, newBreakpointEnd, touchStart, touchMove, touchEnd, dragStart, dragMove, dragEnd.

    Use .on(eventName, callback) to bind a function and .off(eventName, callback) to remove it. The callback receives (info, eventName) where info contains the slider state.

    var customizedFunction = function (info, eventName) {
      // direct access to info object
      console.log(info.event.type, info.container.id);
    }
    
    // bind function to event
    slider.events.on('transitionEnd', customizedFunction);
    
    // remove function binding
    slider.events.off('transitionEnd', customizedFunction);
  8. Use Tiny Slider 2 methods

    master

    Once initialized, the slider returns an object containing several properties and methods to control its behavior. Key methods include:

    • goTo(target): Navigate to a specific slide using a number or keywords ('prev', 'next', 'first', 'last').
    • play(): Start autoplay (requires autoplay: true in options).
    • pause(): Stop autoplay (requires autoplay: true in options).
    • updateSliderHeight(): Manually adjust height when autoHeight is enabled.
    • destroy(): Remove the slider instance.
    • rebuild(): Re-initialize the slider after it has been destroyed. This returns a new slider object with the original options.
    slider.goTo(3);
    slider.goTo('prev');
    slider.goTo('next');
    slider.goTo('first');
    slider.goTo('last');
    
    slider.play();
    slider.pause();
    
    slider.updateSliderHeight();
    
    slider.destroy();
    
    slider = slider.rebuild();
  9. Reference: Tiny Slider configuration options

    master

    The following table lists all available configuration options for Tiny Slider. Note that since v2.0.2, options like container, controlsContainer, navContainer, and autoplayButton can accept CSS selectors as well as DOM elements.

    | Option | Type | Description |
    | --- | --- | --- |
    | `container` | Node \| String | Default: `'.slider'`. <br> The slider container element or selector. |
    | `mode` | "carousel" \| "gallery" | Default: "carousel". <br> Controls animation behaviour. <br> With `carousel` everything slides to the side, while `gallery` uses fade animations and changes all slides at once. |
    | `axis` | "horizontal" \| "vertical" | Default: "horizontal". <br> The axis of the slider. |
    | `items` | positive number | Default: 1. <br> Number of slides being displayed in the viewport. <br> If slides less or equal than `items`, the slider won't be initialized. |
    | `gutter` | positive integer | Default: 0. <br> Space between slides (in "px"). |
    | `edgePadding` | positive integer | Default: 0. <br> Space on the outside (in "px"). |
    | `fixedWidth` | positive integer \| false | Default: false. <br> Controls `width` attribute of the slides. |
    | `autoWidth` | Boolean | Default: false. <br> If `true`, the width of each slide will be its natural width as a `inline-block` box. |
    | `viewportMax` (was `fixedWidthViewportWidth`) | positive integer \| false | Default: false. <br> Maximum viewport width for `fixedWidth`/`autoWidth`. |
    | `slideBy` | positive number \| "page" | Default: 1. <br> Number of slides going on one "click". |
    | `center` (v2.9.2+) | Boolean | Default: false. <br> Center the active slide in the viewport. |
    | `controls` | Boolean | Default: true. <br> Controls the display and functionalities of `controls` components (prev/next buttons). If `true`, display the `controls` and add all functionalities. <br>For better accessibility, when a prev/next button is focused, user will be able to control the slider using left/right arrow keys.|
    | `controlsPosition` | "top" \| "bottom" | Default: "top". <br> Controls `controls` position. |
    | `controlsText` | (Text \| Markup) Array | Default: ["prev", "next"]. <br> Text or markup in the prev/next buttons. |
    | `controlsContainer` | Node \| String \| false | Default: false. <br> The container element/selector around the prev/next buttons. <br> `controlsContainer` must have at least 2 child elements. |
    | `prevButton` | Node \| String \| false | Default: false. <br> Customized previous buttons. <br> This option will be ignored if `controlsContainer` is a Node element or a CSS selector. |
    | `nextButton` | Node \| String \| false | Default: false. <br> Customized next buttons. <br> This option will be ignored if `controlsContainer` is a Node element or a CSS selector. |
    | `nav` | Boolean | Default: true. <br> Controls the display and functionalities of `nav` components (dots). If `true`, display the `nav` and add all functionalities. |
    | `navPosition` | "top" \| "bottom" | Default: "top". <br> Controls `nav` position. |
    | `navContainer` | Node \| String \| false | Default: false. <br> The container element/selector around the dots. <br> `navContainer` must have at least same number of children as the slides. |
    | `navAsThumbnails` | Boolean | Default: false. <br> Indicate if the dots are thumbnails. If `true`, they will always be visible even when more than 1 slides displayed in the viewport. |
    | `arrowKeys` | Boolean | Default: false. <br> Allows using arrow keys to switch slides. |
    | `speed` | positive integer | Default: 300. <br> Speed of the slide animation (in "ms"). |
    | `autoplay` | Boolean | Default: false. <br> Toggles the automatic change of slides. |
    | `autoplayPosition` | "top" \| "bottom" | Default: "top". <br> Controls `autoplay` position. |
    | `autoplayTimeout` | positive integer | Default: 5000. <br> Time between 2 `autoplay` slides change (in "ms"). |
    | `autoplayDirection` | "forward" \| "backward" | Default: "forward". <br> Direction of slide movement (ascending/descending the slide index). |
    | `autoplayText` | Array (Text \| Markup) | Default: ["start", "stop"]. <br> Text or markup in the autoplay start/stop button. |
    | `autoplayHoverPause` | Boolean | Default: false. <br> Stops sliding on mouseover. |
    | `autoplayButton` | Node \| String \| false | Default: false. <br> The customized autoplay start/stop button or selector. |
    | `autoplayButtonOutput` | Boolean | Default: true. <br> Output `autoplayButton` markup when `autoplay` is true but a customized `autoplayButton` is not provided. |
    | `autoplayResetOnVisibility` | Boolean | Default: true. <br> Pauses the sliding when the page is invisible and resumes it when the page become visiable again. ([Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API)) |
    | `animateIn` | String | Default: "tns-fadeIn". <br> Name of intro animation `class`. |
    | `animateOut` | String | Default: "tns-fadeOut". <br> Name of outro animation `class`. |
    | `animateNormal` | String | Default: "tns-normal". <br> Name of default animation `class`. |
    | `animateDelay` | positive integer \| false | Default: false. <br> Time between each `gallery` animation (in "ms"). |
    | `loop` | Boolean | Default: true. <br> Moves throughout all the slides seamlessly. |
    | `rewind` | Boolean | Default: false. <br> Moves to the opposite edge when reaching the first or last slide. |
    | `autoHeight` | Boolean | Default: false. <br> Height of slider container changes according to each slide's height. |
    | `responsive` | Object: { <br>&emsp;breakpoint: { <br>&emsp;&emsp;key: value<br>&emsp;} <br>} \| false | Default: false. <br>Breakpoint: Integer.<br>Defines options for different viewport widths (see [Responsive Options](#responsive-options)). <br> |
    | `lazyload` | Boolean | Default: false. <br> Enables lazyloading images that are currently not viewed, thus saving bandwidth (see [demo](http://ganlanyuan.github.io/tiny-slider/demo/#lazyload_wrapper)). <br> NOTE: <br>+ Class `.tns-lazy-img` need to be set on every image you want to lazyload if option `lazyloadSelector` is not specified; <br>+ `data-src` attribute with its value of the real image `src` is required; <br>+ `width` attribute for every image is required for `autoWidth` slider. |
    | `lazyloadSelector` (v2.9.1+) | String | Default: `'.tns-lazy-img'`. <br> The CSS selector for lazyload images. |
    | `touch` | Boolean | Default: true. <br> Activates input detection for touch devices. |
    | `mouseDrag` | Boolean | Default: false. <br> Changing slides by dragging them. |
    | `swipeAngle` | positive integer \| Boolean | Default: 15. <br> Swipe or drag will not be triggered if the angle is not inside the range when set. |
    | `preventActionWhenRunning` (v2.9.1+) | Boolean | Default: false. <br> Prevent next transition while slider is transforming. |
    | `preventScrollOnTouch` (v2.9.1+) | "auto" \| "force" \| false | Default: false. <br> Prevent page from scrolling on `touchmove`. If set to "auto", the slider will first check if the touch direction matches the slider axis, then decide whether prevent the page scrolling or not. If set to "force", the slider will always prevent the page scrolling. |
    | `nested` | "inner" \| "outer" \| false | Default: false. <br> Define the relationship between nested sliders. (see [demo](http://ganlanyuan.github.io/tiny-slider/demo/#nested_wrapper)) <br>Make sure you run the inner slider first, otherwise the height of the inner slider container will be wrong. |
    | `freezable` | Boolean | Default: true. <br> Indicate whether the slider will be frozen (`controls`, `nav`, `autoplay` and other functions will stop work) when all slides can be displayed in one page. |
    | `disable` | Boolean | Default: false. <br> Disable slider. |
    | `startIndex` | positive integer | Default: 0. <br> The initial `index` of the slider. |
    | `onInit` | Function \| false | Default: false. <br> Callback to be run on initialization. |
    | `useLocalStorage` | Boolean | Default: true. <br> Save browser capability variables to [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and without detecting them everytime the slider runs if set to `true`. |
    | `nonce`| String / false | Default: false. <br> Optional Nonce attribute for inline style tag to allow slider usage without `unsafe-inline Content Security Policy source. |