Skip to content

Repository files navigation

tiny-slider 2.0

version
Tiny slider for all purposes, inspired by Owl Carousel.
Demos
Tests for desktop browsers (running on Firefox 12+, Chrome 15+, Safari 5.1+, Opera 12.1+, IE9+)
Tests for mobile browsers (running on Android Browser 4.2+)
Note: some features may need a manual test.

Previous versions: v1, v0

Contents

+ What's new
+ Features
+ Install
+ Usage
+ Options
+ Responsive options
+ Methods
+ Custom Events
+ Fallback
+ Browser Support
+ Support
+ License

What's new

  • Using % instead of px (No more recalculation of each slide width on window resize)
  • Using CSS Mediaqueries if supported
  • Save browser capbility values to localStorage, so they will not be recheck again until browser get upgraded or user clear the localStorage manuelly.
  • More options available for responsive. (Start from v2.1.0, issue 53)
  • Insert controls and navbefore 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

* Default

Carousel *Gallery
Horizontal *Vertical
Percentage Width *Fixed WidthAuto Width
Loop
Rewind-
Slide by-
Gutter
Edge padding-
Responsive
Lazyload
Autoplay
Auto height
Touch/drag
Arrow keys
Customize controls/nav
Accessibility
Respond to DOM visibility changes
Custom events
Nested

top↑

Install

bower install tiny-slider or npm install tiny-slider

Usage

1. Add CSS (and IE8 polyfills if needed)

<linkrel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.8.6/tiny-slider.css"><!--[if (lt IE 9)]><script src="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.8.6/min/tiny-slider.helper.ie8.js"></script><![endif]-->

2. Add markup

<divclass="my-slider"><div></div><div></div><div></div></div><!-- or ul.my-slider > li -->

3. Call tns()

Add tiny-slider.js to your page:

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

Or import tns via webpack or rollup:

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

Or import tns directly start from v2.8.6

<scripttype="module">import{tns}from'./src/tiny-slider.js';varslider=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 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 (previously fixedWidthViewportWidth)positive integer | falseDefault: false.
Maximum viewport width for fixedWidth/autoWidth.
slideBypositive number | "page"Default: 1.
Number of slides going on one "click".
controlsBooleanDefault: true.
Controls the display and functionalities of controls components (prev/next buttons). If true, display the controls and add all functionalities.
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.
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.
Indecate if the dots are thurbnails. 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.
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 invisiable 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: width attribute for each <img> is required for autoWidth slider.
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.
nested"inner" | "outer" | falseDefault: false.
Difine 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.

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,
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: fixedWidth can only be changed to other positive integers. It can't be changed to negtive 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 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 the getInfo() 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 indexnavCurrent: navCurrent,// current dot indexnavCurrentCached: navCurrentCached,// previous dot indexvisibleNavIndexes: visibleNavIndexes,// visible nav indexesvisibleNavIndexesCached: visibleNavIndexesCached,sheet: sheet,event: e||{},// event object if available};

getInfo

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

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.

varcustomizedFunction=function(info){// 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);

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.

About

Vanilla javascript slider for all purposes.

Resources

Contributing

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages