- Notifications
You must be signed in to change notification settings - Fork789
Vanilla javascript slider for all purposes.
License
ganlanyuan/tiny-slider
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Tiny slider for all purposes, inspired byOwl Carousel.
Warning: tiny-slider works with static content and it works in the browser only. If the HTML is loaded dynamically, make sure to calltns() after its loading.
- What's new
- Features
- Install
- Usage
- Options
- Responsive options
- Methods
- Custom Events
- Fallback
- Browser Support
- Support
- License
- Using
%instead ofpx(No more recalculation of each slide width on window resize) - Using CSS Mediaqueries if supported
- Save browser capability values tolocalStorage, so they will not be recheck again until browser get upgraded or user clear the localStorage manually.
- More options available for
responsive. (Start fromv2.1.0,issue 53) - Insert
controlsandnavbefore slider instead of after (issue 4) - Move
autoplaybutton out ofnavcontainer. (Start fromv2.1.0) - Some selector changes in
tiny-slider.scss
Migrating to v2
- Update
controlsand / ornavstyles based on their position changes. - Update the
slider selectorsaccordingly if used in your CSS or JS. - Update styles related to
autoplaybutton.
| 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 | ✓ | ✓ | ✓ | ✓ | ✓ |
bower install tiny-slider ornpm install tiny-slider
<linkrel="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]-->
<divclass="my-slider"><div></div><div></div><div></div></div><!-- or ul.my-slider > li -->
Option A: Add tiny-slider.js to your page:
<scriptsrc="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: Importtns viawebpack orrollup:
// yourScript.jsimport{tns}from"./node_modules/tiny-slider/src/tiny-slider"
Option C: Importtns directly start from v2.8.2
<scripttype="module">import{tns}from'./src/tiny-slider.js';varslider=tns({container:'.my-slider',items:3,slideBy:'page',autoplay:true});</script>
| Option | Type | Description |
|---|---|---|
container | Node | String | Default:'.slider'.The slider container element or selector. |
mode | "carousel" | "gallery" | Default: "carousel". Controls animation behaviour. With carousel everything slides to the side, whilegallery uses fade animations and changes all slides at once. |
axis | "horizontal" | "vertical" | Default: "horizontal". The axis of the slider. |
items | positive number | Default: 1. Number of slides being displayed in the viewport. If slides less or equal than items, the slider won't be initialized. |
gutter | positive integer | Default: 0. Space between slides (in "px"). |
edgePadding | positive integer | Default: 0. Space on the outside (in "px"). |
fixedWidth | positive integer | false | Default: false. Controls width attribute of the slides. |
autoWidth | Boolean | Default: false. If true, the width of each slide will be its natural width as ainline-block box. |
viewportMax (wasfixedWidthViewportWidth) | positive integer | false | Default: false. Maximum viewport width for fixedWidth/autoWidth. |
slideBy | positive number | "page" | Default: 1. Number of slides going on one "click". |
center (v2.9.2+) | Boolean | Default: false. Center the active slide in the viewport. |
controls | Boolean | Default: true. Controls the display and functionalities of controls components (prev/next buttons). Iftrue, display thecontrols 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) Array | Default: ["prev", "next"]. Text or markup in the prev/next buttons. |
controlsContainer | Node | String | false | Default: false. The container element/selector around the prev/next buttons. controlsContainer must have at least 2 child elements. |
prevButton | Node | String | false | Default: false. Customized previous buttons. This option will be ignored if controlsContainer is a Node element or a CSS selector. |
nextButton | Node | String | false | Default: false. Customized next buttons. This option will be ignored if controlsContainer is a Node element or a CSS selector. |
nav | Boolean | Default: true. Controls the display and functionalities of nav components (dots). Iftrue, display thenav and add all functionalities. |
navPosition | "top" | "bottom" | Default: "top". Controls nav position. |
navContainer | Node | String | false | Default: false. The container element/selector around the dots. navContainer must have at least same number of children as the slides. |
navAsThumbnails | Boolean | Default: false. 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. Allows using arrow keys to switch slides. |
speed | positive integer | Default: 300. Speed of the slide animation (in "ms"). |
autoplay | Boolean | Default: false. Toggles the automatic change of slides. |
autoplayPosition | "top" | "bottom" | Default: "top". Controls autoplay position. |
autoplayTimeout | positive integer | Default: 5000. Time between 2 autoplay slides change (in "ms"). |
autoplayDirection | "forward" | "backward" | Default: "forward". Direction of slide movement (ascending/descending the slide index). |
autoplayText | Array (Text | Markup) | Default: ["start", "stop"]. Text or markup in the autoplay start/stop button. |
autoplayHoverPause | Boolean | Default: false. Stops sliding on mouseover. |
autoplayButton | Node | String | false | Default: false. The customized autoplay start/stop button or selector. |
autoplayButtonOutput | Boolean | Default: true. Output autoplayButton markup whenautoplay is true but a customizedautoplayButton is not provided. |
autoplayResetOnVisibility | Boolean | Default: true. Pauses the sliding when the page is invisible and resumes it when the page become visiable again. (Page Visibility API) |
animateIn | String | Default: "tns-fadeIn". Name of intro animation class. |
animateOut | String | Default: "tns-fadeOut". Name of outro animation class. |
animateNormal | String | Default: "tns-normal". Name of default animation class. |
animateDelay | positive integer | false | Default: false. Time between each gallery animation (in "ms"). |
loop | Boolean | Default: true. Moves throughout all the slides seamlessly. |
rewind | Boolean | Default: false. Moves to the opposite edge when reaching the first or last slide. |
autoHeight | Boolean | Default: false. Height of slider container changes according to each slide's height. |
responsive | Object: { breakpoint: { key: value } } | false | Default: false. Breakpoint: Integer. Defines options for different viewport widths (seeResponsive Options). |
lazyload | Boolean | Default: false. Enables lazyloading images that are currently not viewed, thus saving bandwidth (seedemo). NOTE: + Class .tns-lazy-img need to be set on every image you want to lazyload if optionlazyloadSelector is not specified;+ data-src attribute with its value of the real imagesrc is required;+ width attribute for every image is required forautoWidth slider. |
lazyloadSelector (v2.9.1+) | String | Default:'.tns-lazy-img'.The CSS selector for lazyload images. |
touch | Boolean | Default: true. Activates input detection for touch devices. |
mouseDrag | Boolean | Default: false. Changing slides by dragging them. |
swipeAngle | positive integer | Boolean | Default: 15. Swipe or drag will not be triggered if the angle is not inside the range when set. |
preventActionWhenRunning (v2.9.1+) | Boolean | Default: false. Prevent next transition while slider is transforming. |
preventScrollOnTouch (v2.9.1+) | "auto" | "force" | false | Default: 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" | false | Default: false. Define the relationship between nested sliders. (seedemo) Make sure you run the inner slider first, otherwise the height of the inner slider container will be wrong. |
freezable | Boolean | Default: 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. |
disable | Boolean | Default: false. Disable slider. |
startIndex | positive integer | Default: 0. The initial index of the slider. |
onInit | Function | false | Default: false. Callback to be run on initialization. |
useLocalStorage | Boolean | Default: true. Save browser capability variables tolocalStorage and without detecting them everytime the slider runs if set to true. |
nonce | String / false | Default: 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')
The following options can be redefined inresponsive 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. fixedWidthcan only be changed to other positive integers. It can't be changed to negative integer, 0 or other data type.top↑
The slider returns a slider object with some properties and methods once it's initialized:
{version:version,// tiny-slider versiongetInfo:info(),events:events,// ObjectgoTo:goTo(),play:play(),pause:pause(),isOn:isOn,// BooleanupdateSliderHeight:updateInnerWrapperHeight(),refresh:initSliderTransform(),destroy:destroy(),rebuild:rebuild()}
To get the slider information, you can either use thegetInfo() method or subscribe to an Event. Both return an Object:
{container:container,// slider containerslideItems:slideItems,// slides listnavContainer:navContainer,// nav containernavItems:navItems,// dots listcontrolsContainer:controlsContainer,// controls containerhasControls:hasControls,// indicate if controls existprevButton:prevButton,// previous buttonnextButton:nextButton,// next buttonitems:items,// items on a pageslideBy:slideBy// items slide bycloneCount:cloneCount,// cloned slide countslideCount:slideCount,// original slide countslideCountNew:slideCountNew,// total slide count after initializationindex:index,// current indexindexCached:indexCached,// previous indexdisplayIndex:getCurrentSlide(),// display index starts from 1navCurrent:navCurrent,// current dot indexnavCurrentCached:navCurrentCached,// previous dot indexpages:pages,// visible nav indexespagesCached:pagesCached,sheet:sheet,event:e||{},// event object if available};
Get slider information.
slider.getInfo();document.querySelector('.next-button').onclick=function(){// get slider infovarinfo=slider.getInfo(),indexPrev=info.indexCached,indexCurrent=info.index;// update style based on indexinfo.slideItems[indexPrev].classList.remove('active');info.slideItems[indexCurrent].classList.add('active');};
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);};
Programmatically start slider autoplay whenautoplay: true.
slider.play();
Programmatically stop slider autoplay whenautoplay: true.
slider.pause();
Manually adjust slider height whenautoHeight istrue.
slider.updateSliderHeight();
Destroy the slider.
slider.destroy();
Rebuild the slider after destroy.
slider=slider.rebuild();// this method returns a new slider Object with the same options with the original slider
Available events include:indexChanged,transitionStart,transitionEnd,newBreakpointStart,newBreakpointEnd,touchStart,touchMove,touchEnd,dragStart,dragMove anddragEnd.
varcustomizedFunction=function(info,eventName){// direct access to info objectconsole.log(info.event.type,info.container.id);}// bind function to eventslider.events.on('transitionEnd',customizedFunction);// remove function bindingslider.events.off('transitionEnd',customizedFunction);
.no-js .your-slider {overflow-x: auto; }.no-js .your-slider>div {float: none; }
Desktop:Firefox 8+ ✓Chrome 15+ ✓ (Should works onChrome 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+ ✓
Live tests and Automated Tests
Live tests, Screenshots and Automated Tests
Cdnjs
Images on demo page are fromhttps://unsplash.com/.
This project is available under theMIT license.
About
Vanilla javascript slider for all purposes.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.