Convert Figma logo to code with AI

ganlanyuan logotiny-slider

Vanilla javascript slider for all purposes.

5,235
784
5,235
382

Top Related Projects

39,523

Most modern mobile touch slider with hardware accelerated transitions

28,370

the last carousel you'll ever need

4,828

Splide is a lightweight, flexible and accessible slider/carousel written in TypeScript. No dependencies, no Lighthouse errors.

7,271

A dependency-free JavaScript ES6 slider and carousel. It’s lightweight, flexible and fast. Designed to slide. No less, no more

🎠 A carousel component for Vue.js

JQuery lightSlider is a lightweight responsive Content slider with carousel thumbnails navigation

Quick Overview

Tiny Slider is a lightweight, vanilla JavaScript slider library with no dependencies. It's designed to be responsive, touch-friendly, and customizable, making it suitable for various web projects ranging from simple image carousels to complex content sliders.

Pros

  • Lightweight and fast, with no external dependencies
  • Highly customizable with numerous options and callbacks
  • Responsive and touch-friendly, working well on mobile devices
  • Supports various content types, including images, HTML, and lazy loading

Cons

  • Limited built-in styling options, requiring custom CSS for advanced designs
  • May have a steeper learning curve compared to some jQuery-based alternatives
  • Documentation could be more comprehensive for some advanced features
  • Occasional issues with specific browser versions or edge cases

Code Examples

Creating a basic slider:

const slider = tns({
  container: '.my-slider',
  items: 3,
  slideBy: 'page',
  autoplay: true
});

Customizing controls and navigation:

const slider = tns({
  container: '.my-slider',
  controlsPosition: 'bottom',
  navPosition: 'top',
  controlsText: ['<', '>'],
  navAsThumbnails: true
});

Using callbacks for custom behavior:

const slider = tns({
  container: '.my-slider',
  onInit: function() {
    console.log('Slider initialized');
  },
  onTransitionEnd: function(info) {
    console.log('Slide changed to:', info.index);
  }
});

Getting Started

  1. Include the Tiny Slider CSS and JS files in your HTML:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.4/tiny-slider.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.4/min/tiny-slider.js"></script>
  1. Create your HTML structure:
<div class="my-slider">
  <div>Slide 1</div>
  <div>Slide 2</div>
  <div>Slide 3</div>
</div>
  1. Initialize the slider in your JavaScript:
const slider = tns({
  container: '.my-slider',
  items: 1,
  slideBy: 'page',
  autoplay: true
});

This will create a basic auto-playing slider with one item visible at a time. Customize the options as needed for your specific use case.

Competitor Comparisons

39,523

Most modern mobile touch slider with hardware accelerated transitions

Pros of Swiper

  • More feature-rich with advanced functionality like parallax effects and virtual slides
  • Larger community and ecosystem, with extensive documentation and plugins
  • Better support for modern frameworks like React, Vue, and Angular

Cons of Swiper

  • Larger file size, which may impact page load times
  • Steeper learning curve due to more complex API and configuration options
  • May be overkill for simple slider needs, potentially leading to unnecessary bloat

Code Comparison

Tiny Slider initialization:

var slider = tns({
  container: '.my-slider',
  items: 3,
  slideBy: 'page',
  autoplay: true
});

Swiper initialization:

const swiper = new Swiper('.swiper-container', {
  slidesPerView: 3,
  spaceBetween: 30,
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});

Both libraries offer simple initialization, but Swiper provides more configuration options out of the box. Tiny Slider focuses on a more streamlined approach, while Swiper offers greater flexibility at the cost of increased complexity.

28,370

the last carousel you'll ever need

Pros of Slick

  • More extensive feature set, including responsive breakpoints and multiple slide layouts
  • Larger community and ecosystem, with more third-party plugins and extensions
  • Better documentation and examples for various use cases

Cons of Slick

  • Larger file size and potentially heavier performance impact
  • Requires jQuery as a dependency, which may not be ideal for modern projects
  • Less frequent updates and maintenance compared to Tiny Slider

Code Comparison

Slick initialization:

$('.slider').slick({
  slidesToShow: 3,
  slidesToScroll: 1,
  autoplay: true,
  autoplaySpeed: 2000,
});

Tiny Slider initialization:

var slider = tns({
  container: '.slider',
  items: 3,
  slideBy: 1,
  autoplay: true,
  autoplayTimeout: 2000,
});

Both libraries offer similar basic functionality, but Slick's syntax is more jQuery-centric, while Tiny Slider uses a more modern JavaScript approach. Tiny Slider provides a smaller footprint and vanilla JavaScript implementation, making it potentially more suitable for lightweight projects or those not using jQuery. Slick, on the other hand, offers more advanced features and customization options out of the box, which may be beneficial for complex slider requirements.

4,828

Splide is a lightweight, flexible and accessible slider/carousel written in TypeScript. No dependencies, no Lighthouse errors.

Pros of Splide

  • More modern and actively maintained, with frequent updates
  • Offers a wider range of features and customization options
  • Better TypeScript support and documentation

Cons of Splide

  • Larger file size compared to Tiny Slider
  • Steeper learning curve due to more complex API

Code Comparison

Tiny Slider initialization:

var slider = tns({
  container: '.my-slider',
  items: 3,
  slideBy: 'page',
  autoplay: true
});

Splide initialization:

new Splide('.splide', {
  type: 'loop',
  perPage: 3,
  autoplay: true
}).mount();

Both libraries offer similar basic functionality, but Splide provides more advanced options for customization and control. Tiny Slider has a simpler API, making it easier to set up for basic use cases. However, Splide's more comprehensive feature set and active development make it a stronger choice for complex projects or those requiring long-term support.

Splide also offers better performance optimization and smoother animations, which can be crucial for larger applications or websites with heavy traffic. On the other hand, Tiny Slider's smaller file size may be advantageous for projects where minimizing load times is a top priority.

7,271

A dependency-free JavaScript ES6 slider and carousel. It’s lightweight, flexible and fast. Designed to slide. No less, no more

Pros of Glide

  • Modular architecture allows for easy customization and extension
  • Supports both mouse and touch events out of the box
  • Smaller file size, leading to faster load times

Cons of Glide

  • Less extensive documentation compared to Tiny Slider
  • Fewer built-in features and options
  • May require more manual configuration for complex setups

Code Comparison

Tiny Slider initialization:

var slider = tns({
  container: '.my-slider',
  items: 3,
  slideBy: 'page',
  autoplay: true
});

Glide initialization:

new Glide('.glide', {
  type: 'carousel',
  perView: 3,
  autoplay: 3000
}).mount();

Both libraries offer simple initialization, but Tiny Slider provides more options in the initial setup, while Glide focuses on a cleaner, more minimal API. Tiny Slider's syntax is more descriptive, using full words like container and slideBy, whereas Glide uses more concise terms like perView.

Glide's modular approach allows for easier customization and extension, making it more flexible for advanced users. However, Tiny Slider offers more built-in features and options out of the box, which can be beneficial for quick implementations or less experienced developers.

In terms of performance, Glide generally has a smaller file size, which can lead to faster load times. However, Tiny Slider offers more comprehensive browser support and may handle complex scenarios more robustly.

🎠 A carousel component for Vue.js

Pros of vue-agile

  • Specifically designed for Vue.js, offering seamless integration with Vue projects
  • Provides Vue-specific features like scoped slots for customization
  • Lightweight and focused on Vue.js ecosystem

Cons of vue-agile

  • Limited to Vue.js projects, not suitable for vanilla JavaScript or other frameworks
  • Fewer overall features compared to tiny-slider
  • Smaller community and potentially less frequent updates

Code Comparison

vue-agile:

<template>
  <agile>
    <div class="slide">Slide 1</div>
    <div class="slide">Slide 2</div>
    <div class="slide">Slide 3</div>
  </agile>
</template>

tiny-slider:

<div class="my-slider">
  <div>Slide 1</div>
  <div>Slide 2</div>
  <div>Slide 3</div>
</div>
<script>
  tns({
    container: '.my-slider',
    items: 1,
    slideBy: 'page',
    autoplay: true
  });
</script>

The code comparison shows that vue-agile uses a Vue component approach, while tiny-slider uses a more traditional HTML structure with JavaScript initialization. vue-agile's syntax is more Vue-friendly, whereas tiny-slider offers a solution that can be used in various JavaScript environments.

JQuery lightSlider is a lightweight responsive Content slider with carousel thumbnails navigation

Pros of LightSlider

  • Supports more customization options out of the box
  • Includes built-in responsive breakpoints
  • Offers a wider range of animation effects

Cons of LightSlider

  • Larger file size, potentially impacting page load times
  • Less frequently updated compared to Tiny Slider
  • May have more complex setup for basic use cases

Code Comparison

LightSlider:

$("#lightSlider").lightSlider({
    item: 3,
    autoWidth: false,
    slideMove: 1,
    slideMargin: 10
});

Tiny Slider:

var slider = tns({
    container: '.my-slider',
    items: 3,
    gutter: 10,
    slideBy: 1
});

Both libraries offer similar functionality for creating responsive sliders, but their syntax and configuration options differ. LightSlider uses jQuery and offers more granular control over slider behavior, while Tiny Slider is a vanilla JavaScript solution with a more streamlined API.

LightSlider provides more built-in features and customization options, making it suitable for complex slider requirements. However, this comes at the cost of a larger file size and potential performance impact.

Tiny Slider, on the other hand, focuses on being lightweight and performant, making it a good choice for projects where minimizing resource usage is a priority. It may require additional custom code for more advanced features, but its smaller footprint and regular updates make it an attractive option for many developers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Tiny Slider 2

version

Tiny slider for all purposes, inspired by Owl Carousel.

Demos

Test results

Previous versions: v1, v0

Warning: tiny-slider works with static content and it works in the browser only. If the HTML is loaded dynamically, make sure to call tns() after its loading.

Contents

What's new

  • Using % instead of px (No more recalculation of each slide width on window resize)
  • Using CSS Mediaqueries if supported
  • Save browser capability values to localStorage, so they will not be recheck again until browser get upgraded or user clear the localStorage manually.
  • More options available for responsive. (Start from v2.1.0, issue 53)
  • Insert controls and nav before slider instead of after (issue 4)
  • Move autoplay button out of nav container. (Start from v2.1.0)
  • Some selector changes in tiny-slider.scss

Migrating to v2

  • Update controls and / or nav styles based on their position changes.
  • Update the slider selectors accordingly if used in your CSS or JS.
  • Update styles related to autoplay button.

top↑

Features

  Carousel * Gallery
Horizontal * Vertical
Percentage Width * Fixed Width Auto Width
Loop ✓ ✓ ✓ ✓ ✓
Rewind ✓ ✓ ✓ ✓  
Slide by ✓ ✓ ✓ ✓  
Gutter ✓ ✓ ✓ ✓ ✓
Edge padding ✓ ✓ ✓ ✓  
Center (v2.9.2+) ✓ ✓ ✓    
Responsive ✓ ✓ ✓ ✓ ✓
Lazyload ✓ ✓ ✓ ✓ ✓
Autoplay ✓ ✓ ✓ ✓ ✓
Auto height ✓ ✓ ✓ ✓ ✓
Touch/drag ✓ ✓ ✓ ✓ ✓
Arrow keys ✓ ✓ ✓ ✓ ✓
Customize controls/nav ✓ ✓ ✓ ✓ ✓
Accessibility ✓ ✓ ✓ ✓ ✓
Respond to DOM visibility changes ✓ ✓ ✓ ✓ ✓
Custom events ✓ ✓ ✓ ✓ ✓
Nested ✓ ✓ ✓ ✓ ✓
* Default

top↑

Install

bower install tiny-slider or npm install tiny-slider

Usage

1. Add CSS (and IE8 polyfills if needed)

<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></div>
  <div></div>
  <div></div>
</div>
<!-- or ul.my-slider > li -->

3. Call tns()

Option A: Add tiny-slider.js to your page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.2/min/tiny-slider.js"></script>
<!-- NOTE: prior to v2.2.1 tiny-slider.js need to be in <body> -->

Option B: Import tns via webpack or rollup:

// yourScript.js
import { tns } from "./node_modules/tiny-slider/src/tiny-slider"

Option C: Import tns directly start from v2.8.2

<script type="module">
  import {tns} from './src/tiny-slider.js';

  var slider = tns({
    container: '.my-slider',
    items: 3,
    slideBy: 'page',
    autoplay: true
  });
  </script>

top↑

Options

OptionTypeDescription
containerNode | StringDefault: '.slider'.
The slider container element or selector.
mode"carousel" | "gallery"Default: "carousel".
Controls animation behaviour.
With carousel everything slides to the side, while gallery uses fade animations and changes all slides at once.
axis"horizontal" | "vertical"Default: "horizontal".
The axis of the slider.
itemspositive numberDefault: 1.
Number of slides being displayed in the viewport.
If slides less or equal than items, the slider won't be initialized.
gutterpositive integerDefault: 0.
Space between slides (in "px").
edgePaddingpositive integerDefault: 0.
Space on the outside (in "px").
fixedWidthpositive integer | falseDefault: false.
Controls width attribute of the slides.
autoWidthBooleanDefault: false.
If true, the width of each slide will be its natural width as a inline-block box.
viewportMax (was fixedWidthViewportWidth)positive integer | falseDefault: false.
Maximum viewport width for fixedWidth/autoWidth.
slideBypositive number | "page"Default: 1.
Number of slides going on one "click".
center (v2.9.2+)BooleanDefault: false.
Center the active slide in the viewport.
controlsBooleanDefault: true.
Controls the display and functionalities of controls components (prev/next buttons). If true, display the controls and add all functionalities.
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".
Controls controls position.
controlsText(Text | Markup) ArrayDefault: ["prev", "next"].
Text or markup in the prev/next buttons.
controlsContainerNode | String | falseDefault: false.
The container element/selector around the prev/next buttons.
controlsContainer must have at least 2 child elements.
prevButtonNode | String | falseDefault: false.
Customized previous buttons.
This option will be ignored if controlsContainer is a Node element or a CSS selector.
nextButtonNode | String | falseDefault: false.
Customized next buttons.
This option will be ignored if controlsContainer is a Node element or a CSS selector.
navBooleanDefault: true.
Controls the display and functionalities of nav components (dots). If true, display the nav and add all functionalities.
navPosition"top" | "bottom"Default: "top".
Controls nav position.
navContainerNode | String | falseDefault: false.
The container element/selector around the dots.
navContainer must have at least same number of children as the slides.
navAsThumbnailsBooleanDefault: false.
Indicate if the dots are thumbnails. If true, they will always be visible even when more than 1 slides displayed in the viewport.
arrowKeysBooleanDefault: false.
Allows using arrow keys to switch slides.
speedpositive integerDefault: 300.
Speed of the slide animation (in "ms").
autoplayBooleanDefault: false.
Toggles the automatic change of slides.
autoplayPosition"top" | "bottom"Default: "top".
Controls autoplay position.
autoplayTimeoutpositive integerDefault: 5000.
Time between 2 autoplay slides change (in "ms").
autoplayDirection"forward" | "backward"Default: "forward".
Direction of slide movement (ascending/descending the slide index).
autoplayTextArray (Text | Markup)Default: ["start", "stop"].
Text or markup in the autoplay start/stop button.
autoplayHoverPauseBooleanDefault: false.
Stops sliding on mouseover.
autoplayButtonNode | String | falseDefault: false.
The customized autoplay start/stop button or selector.
autoplayButtonOutputBooleanDefault: true.
Output autoplayButton markup when autoplay is true but a customized autoplayButton is not provided.
autoplayResetOnVisibilityBooleanDefault: true.
Pauses the sliding when the page is invisible and resumes it when the page become visiable again. (Page Visibility API)
animateInStringDefault: "tns-fadeIn".
Name of intro animation class.
animateOutStringDefault: "tns-fadeOut".
Name of outro animation class.
animateNormalStringDefault: "tns-normal".
Name of default animation class.
animateDelaypositive integer | falseDefault: false.
Time between each gallery animation (in "ms").
loopBooleanDefault: true.
Moves throughout all the slides seamlessly.
rewindBooleanDefault: false.
Moves to the opposite edge when reaching the first or last slide.
autoHeightBooleanDefault: false.
Height of slider container changes according to each slide's height.
responsiveObject: {
 breakpoint: {
  key: value
 }
} | false
Default: false.
Breakpoint: Integer.
Defines options for different viewport widths (see Responsive Options).
lazyloadBooleanDefault: false.
Enables lazyloading images that are currently not viewed, thus saving bandwidth (see demo).
NOTE:
+ Class .tns-lazy-img need to be set on every image you want to lazyload if option lazyloadSelector is not specified;
+ data-src attribute with its value of the real image src is required;
+ width attribute for every image is required for autoWidth slider.
lazyloadSelector (v2.9.1+)StringDefault: '.tns-lazy-img'.
The CSS selector for lazyload images.
touchBooleanDefault: true.
Activates input detection for touch devices.
mouseDragBooleanDefault: false.
Changing slides by dragging them.
swipeAnglepositive integer | BooleanDefault: 15.
Swipe or drag will not be triggered if the angle is not inside the range when set.
preventActionWhenRunning (v2.9.1+)BooleanDefault: false.
Prevent next transition while slider is transforming.
preventScrollOnTouch (v2.9.1+)"auto" | "force" | falseDefault: false.
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" | falseDefault: false.
Define the relationship between nested sliders. (see demo)
Make sure you run the inner slider first, otherwise the height of the inner slider container will be wrong.
freezableBooleanDefault: true.
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.
disableBooleanDefault: false.
Disable slider.
startIndexpositive integerDefault: 0.
The initial index of the slider.
onInitFunction | falseDefault: false.
Callback to be run on initialization.
useLocalStorageBooleanDefault: true.
Save browser capability variables to localStorage and without detecting them everytime the slider runs if set to true.
nonceString / falseDefault: false.
Optional Nonce attribute for inline style tag to allow slider usage without `unsafe-inline Content Security Policy source.

NOTE: Prior to v2.0.2, options "container", "controlsContainer", "navContainer" and "autoplayButton" still need to be DOM elements. E.g. container: document.querySelector('.my-slider')

top↑

Responsive options

The following options can be redefined in responsive field: startIndex, items, slideBy, speed, autoHeight, fixedWidth, edgePadding, gutter, center, controls, controlsText, nav, autoplay, autoplayHoverPause, autoplayResetOnVisibility, autoplayText, autoplayTimeout, touch, mouseDrag, arrowKeys, disable

<script>
  var slider = tns({
    container: '.my-slider',
    items: 1,
    responsive: {
      640: {
        edgePadding: 20,
        gutter: 20,
        items: 2
      },
      700: {
        gutter: 30
      },
      900: {
        items: 3
      }
    }
  });
</script>

NOTE:

  • The breakpoints behave like (min-width: breakpoint) in CSS, so an undefined option will be inherited from previous small breakpoints.
  • fixedWidth can only be changed to other positive integers. It can't be changed to negative integer, 0 or other data type. top↑

Methods

The slider returns a slider object with some properties and methods once it's initialized:

{
  version: version, // tiny-slider version
  getInfo: info(),
  events: events, // Object
  goTo: goTo(),
  play: play(),
  pause: pause(),
  isOn: isOn, // Boolean
  updateSliderHeight: updateInnerWrapperHeight(),
  refresh: initSliderTransform(),
  destroy: destroy(),
  rebuild: rebuild()
}

To get the slider information, you can either use the getInfo() method or subscribe to an Event. Both return an Object:

{
                container: container, // slider container
               slideItems: slideItems, // slides list
             navContainer: navContainer, // nav container
                 navItems: navItems, // dots list
        controlsContainer: controlsContainer, // controls container
              hasControls: hasControls, // indicate if controls exist
               prevButton: prevButton, // previous button
               nextButton: nextButton, // next button
                    items: items, // items on a page
                  slideBy: slideBy // items slide by
               cloneCount: cloneCount, // cloned slide count
               slideCount: slideCount, // original slide count
            slideCountNew: slideCountNew, // total slide count after initialization
                    index: index, // current index
              indexCached: indexCached, // previous index
             displayIndex: getCurrentSlide(), // display index starts from 1
               navCurrent: navCurrent, // current dot index
         navCurrentCached: navCurrentCached, // previous dot index
                    pages: pages, // visible nav indexes
              pagesCached: pagesCached,
                    sheet: sheet,
                    event: e || {}, // event object if available
};

getInfo

Get slider information.

slider.getInfo();

document.querySelector('.next-button').onclick = function () {
  // get slider info
  var info = slider.getInfo(),
      indexPrev = info.indexCached,
      indexCurrent = info.index;

  // update style based on index
  info.slideItems[indexPrev].classList.remove('active');
  info.slideItems[indexCurrent].classList.add('active');
};

goTo

Go to specific slide by number or keywords.

slider.goTo(3);
slider.goTo('prev');
slider.goTo('next');
slider.goTo('first');
slider.goTo('last');

document.querySelector('.goto-button').onclick = function () {
  slider.goTo(3);
};

play

Programmatically start slider autoplay when autoplay: true.

slider.play();

pause

Programmatically stop slider autoplay when autoplay: true.

slider.pause();

updateSliderHeight

Manually adjust slider height when autoHeight is true.

slider.updateSliderHeight();

destroy

Destroy the slider.

slider.destroy();

rebuild

Rebuild the slider after destroy.

slider = slider.rebuild();
// this method returns a new slider Object with the same options with the original slider

Custom Events

Available events include: indexChanged, transitionStart, transitionEnd, newBreakpointStart, newBreakpointEnd, touchStart, touchMove, touchEnd, dragStart, dragMove and dragEnd.

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);

top↑

Fallback

.no-js .your-slider { overflow-x: auto; }
.no-js .your-slider > div { float: none; }

Browser Support

Desktop: Firefox 8+ ✓ Chrome 15+ ✓ (Should works on Chrome 4-14 as well, but I couldn't test it.) Safari 4+ ✓ Opera 12.1+ ✓ IE 8+ ✓

Mobile: Android Browser 4.2+ ✓ Chrome Mobile 63+ ✓ Firefox Mobile 28+ ✓ Maxthon 4+ ✓

Support

Browser Stack
Live tests and Automated Tests

Cross Browser Testing
Live tests, Screenshots and Automated Tests

Cdnjs
Images on demo page are from https://unsplash.com/.

License

This project is available under the MIT license.

NPM DownloadsLast 30 Days