GithubHelp home page GithubHelp logo

ganlanyuan / tiny-slider Goto Github PK

View Code? Open in Web Editor NEW
5.2K 74.0 779.0 52.76 MB

Vanilla javascript slider for all purposes.

License: MIT License

CSS 1.39% JavaScript 43.70% HTML 50.40% SCSS 0.33% Nunjucks 4.18%
slider carousel

tiny-slider's Introduction

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

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, while gallery 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 a inline-block box.
viewportMax (was fixedWidthViewportWidth) 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). 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) 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). If true, display the nav 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 when autoplay is true but a customized autoplayButton 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 (see Responsive Options).
lazyload Boolean Default: 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+) 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. (see demo)
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 to localStorage 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')

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.

tiny-slider's People

Contributors

aberezkin avatar alekshs avatar crenshaw-dev avatar daphnesmit avatar dependabot[bot] avatar dimagashko avatar entozoon avatar faboulaws avatar floq-design avatar ganlanyuan avatar hlcfan avatar jamie0 avatar mick-feller avatar nfourtythree avatar nghiepdev avatar notiv-nt avatar openscript avatar przemkow avatar raiondesu avatar reubano avatar rodrigotomees avatar romelgomez avatar s1syphos avatar scottleblang avatar sephreed avatar sfurlong-ae avatar t7yang avatar tabakowy avatar tzsk avatar wroughtec avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tiny-slider's Issues

Resize bug when using responsive option with nav turned off

Steps to reproduce

I am using the slider with these options:

return tns({
  container: carousel,
  items: 1,
  edgePadding: 20,
  responsive: {
    681: 2,
    1360: 4
  },
  slideBy: 'page',
  nav: false,
  loop: false

When I resize between breakpoints, the carousel item display breaks and errors like this are thrown in the console:

Uncaught TypeError: Cannot read property '1' of undefined
    at jt (tiny-slider.js:1896)
    at Tt (tiny-slider.js:1952)
    at tiny-slider.js:1967

Proposed resolution

I've tracked it down to this code:

if (items !== itemsTem && !options.navContainer) {
  updateNavDisplay();
  updateNavStatus();
}

The problem is that updateNavDisplay() and updateNavStatus() are being called, even if nav is false. It can be fixed by changing it to:

if (items !== itemsTem && options.nav && !options.navContainer) {
  updateNavDisplay();
  updateNavStatus();
}

Note: I attempted to fork the repository and create a pull request, but was not able to run the Gulp tasks that turn src into dist. It seems this is because package.json doesn't list the packages used within the gulpfile, but I even ran npm install for all of them manually, and was still getting errors when running gulp script. Am I missing something or approaching this incorrectly?

Regardless, thanks for your work on this! It's the smallest carousel written in vanilla JS that accomplishes everything we need.

Nav buttons are not working properly in gallery mode

How to reproduce :
set 'mode' option to 'gallery'
click once on "prev", "next" or a nav button -> works as expected
click again on any of these buttons -> works not as expected : nothing happen

you can see it on the test page on the "animation" test

screenshot

control buttons doesn't work after swipe / at loop: false

Hey, I found 2 problems with control buttons.

  1. After swiping with fingers on mobile devices the contol buttons seem not to work. However, after page reload and without swiping control buttons work fine.

  2. When loop is deactivated, control buttons doesn't work.

I use webpack.

What could be wrong?

Feature Request: rewind option

when rewind is enabled, the next button is not disabled when the last slide is reached. Clicking it would jump back to the first slide.

[https://github.com//pull/10](see pull request)

Tiny-Slider fails to even start

Asking a question or submit a bug?

  • Question
  • [ x] Bug

How can others reproduce the issue?
It can be reproduced by following the "usage" instructions step by step or simply copy pasting them.

Console error output:

tiny-slider.js:430 Uncaught TypeError: Cannot read property 'appendChild' of null
at calc (tiny-slider.js:430)
at tiny-slider.js:748
at tiny-slider.js:2726
calc @ tiny-slider.js:430
(anonymous) @ tiny-slider.js:748
(anonymous) @ tiny-slider.js:2726
(index):53 Uncaught TypeError: tns is not a function
at HTMLDocument. ((index):53)

Tiny-slider version: 2.0
Browser version: anything

Issues when importing via Webpack

Hi,

I'm trying to use this library along with Webpack. But when I import it like this:

import tinySlider from 'tiny-slider'
console.log(tinySlider)

It imports only one empty object ( => {}).
Am I doing anything wrong? Is it actually possible to use it this way?

Go to first & last

I cannot find a method to programmatically go to the first or last item. I would like to add custom buttons to slide to the first or last item. Is there a way to do this, or is such feature planned (slideTo() or similar)?

README example code bug

In the README you use the following example:

var slider = tinySlider(...);
// init
a.init();

What the heck is a? Should this be: slider.init()?

controlsContainer for custom next/prev

I'm not able to get custom controls working. Is it possible you might update doc with a complete working example?

Taking the simple example provided, simply adding my own 'controls' results in my buttons shown along with the default ones, whether I use 'controls' class or call it 'my-controls' etc.

<div class="my-slider">..</div>

<div class="my-controls">
  <button>my prev</button>
  <button>my next</button>
</div>

My dom ready code looks like this:

             this.tinySlider = this.tinySliderModule({
        	  container: document.querySelector('.my-slider'),
        	  controlsContainer: document.querySelector('.my-controls'),
                  slideBy: 'page',
                  items: 3,
                  gutter: 10,
                  arrowKeys: true
            });

It simply fails with unclear errors. if I remove controlsContainer I get default buttons and the slider works.

TypeError: Cannot read property 'item' of undefined
    at Object.gn.isNodeList
    at setAttrs
    at navInit 
    at sliderInit 

Bower dependency when using the npm package?

Thanks for making this. Just what I needed. But..

If I do npm install tiny-slider the library is installed just fine. I import it in my JavaScript component with import { tns } from 'tiny-slider/src/tiny-slider.module';. When I build Webpack the path resolves just fine to the installed npm package. However, in the tine-slider.module-file there is a dependency on go-native - a library that does not exist as an npm package, and thus a library that is not listed in the package.json either. Hence, the reference in tiny-slider.module to ../../go-native* (the go-native folder in node_modules) is not resolved correctly, which makes my Webpack build fail.

Am I doing something wrong?

Issue: when i used custome arrow

Hi,
I found one issue slider not working once you reached in last slide and again click on next after then slider doesn't work.

my code is:
var slider = tns({
container: document.querySelector('.slider'),
items: 1,
controlsText: ['', ''],
loop: false,
speed: 250,
autoplay: false,

			controlsContainer: document.querySelector('.customize-tools .controls') 	    
       }); 

can u please look this issue.

Thanks

Event listener not working with content added through AJAX

Hello,

I am new to AJAX and trying to understand what's going on here. My slider is added to the DOM with an AJAX call so I'm trying to initialized the script after the content has been added. Right now I just append the script with the following code:

var code = "var slider = tns({items: 1, slideBy: 'page', container: document.getElementsByClassName('slider')[0], nav: true, arrowKeys: true, loop: false, rewind: true, touch: true});";
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);

The problem is that everything is working except the click events. I've read a bit about event delegation but I am not sure how to implement it with Tiny Slider, could you point me in the right direction?

Thanks a lot!

lazyload not working

I get a JS error "Cannot read property 'querySelectorAll' of undefined" when I try to use the lazyload feature. I've used the lazyload example taken from the docs. I'm using the tiny-slider.min.js (not go-native).

"responsive" not working in v1.6.1

Asking a question or submit a bug?

  • Question
  • Bug

I needed the responsive function to change my slider behavior in different browser sizes but this still won't work. Any troubles while using picture elements?
Hope you might help me, thanks!

How can others reproduce the issue?
Live link or Code example:
HTML:

        <ul class="slider">
                <li>
                    <div class="image-wrapper">
                        <picture>
                            <!--[if IE 9]><video style="display:none"><![endif]-->
                            <source media="(max-width: 767px)" srcset="assets/images/team/team1.jpg 1x, assets/images/team/team1.jpg 1.5x">
                            <source media="(max-width: 1023px)" srcset="assets/images/team/team1.jpg 1x, assets/images/team/team1.jpg 1.5x">
                            <source media="(max-width: 1279px)" srcset="assets/images/team/team1.jpg 1x, assets/images/team/team1.jpg 1.5x">
                            <source srcset="assets/images/team/team1.jpg 1x, assets/images/team/team1.jpg 1.5x">
                            <!--[if IE 9]></video><![endif]-->
                            <img src="assets/images/team/team1.jpg" />
                        </picture>
                    </div>
                    <h4>Title</h4>
                </li>
                <li>
                    <div class="image-wrapper">
                        <picture>
                            <!--[if IE 9]><video style="display:none"><![endif]-->
                            <source media="(max-width: 767px)" srcset="assets/images/team/team2.jpg 1x, assets/images/team/team2.jpg 1.5x">
                            <source media="(max-width: 1023px)" srcset="assets/images/team/team2.jpg 1x, assets/images/team/team2.jpg 1.5x">
                            <source media="(max-width: 1279px)" srcset="assets/images/team/team2.jpg 1x, assets/images/team/team2.jpg 1.5x">
                            <source srcset="assets/images/team/team2.jpg 1x, assets/images/team/team2.jpg 1.5x">
                            <!--[if IE 9]></video><![endif]-->
                            <img src="assets/images/team/team2.jpg" />
                        </picture>
                    </div>
                    <h4>Title</h4>
                </li>
                <li>
                    <div class="image-wrapper">
                        <picture>
                            <!--[if IE 9]><video style="display:none"><![endif]-->
                            <source media="(max-width: 767px)" srcset="assets/images/team/team3.jpg 1x, assets/images/team/team3.jpg 1.5x">
                            <source media="(max-width: 1023px)" srcset="assets/images/team/team3.jpg 1x, assets/images/team/team3.jpg 1.5x">
                            <source media="(max-width: 1279px)" srcset="assets/images/team/team3.jpg 1x, assets/images/team/team3.jpg 1.5x">
                            <source srcset="assets/images/team/team3.jpg 1x, assets/images/team/team3.jpg 1.5x">
                            <!--[if IE 9]></video><![endif]-->
                            <img src="assets/images/team/team3.jpg" />
                        </picture>
                    </div>
                    <h4>Title</h4>
                </li>
                <li>
                    <div class="image-wrapper">
                        <picture>
                            <!--[if IE 9]><video style="display:none"><![endif]-->
                            <source media="(max-width: 767px)" srcset="assets/images/team/team4.jpg 1x, assets/images/team/team4.jpg 1.5x">
                            <source media="(max-width: 1023px)" srcset="assets/images/team/team4.jpg 1x, assets/images/team/team4.jpg 1.5x">
                            <source media="(max-width: 1279px)" srcset="assets/images/team/team4.jpg 1x, assets/images/team/team4.jpg 1.5x">
                            <source srcset="assets/images/team/team4.jpg 1x, assets/images/team/team4.jpg 1.5x">
                            <!--[if IE 9]></video><![endif]-->
                            <img src="assets/images/team/team4.jpg" />
                        </picture>
                    </div>
                    <h4>Title</h4>
                </li>
            </ul>

JS:

tns({
container: document.querySelectorAll('.slider')[0],
arrowKeys: true,
loop: true,
items: 1,
lazyload: true,
gutter: 0,
controlsText: [' ', ' '],
responsive: {
700: {
items: 2,
gutter: 27
},
768: {
items: 3,
gutter: 30
},
1024: {
items: 4,
gutter: 50
}
}
});

Tiny-slider version: v1.6.1
Browser version: safari, chrome, opera, firefox (current versions)

class for disabled nav button

Hi William,

Thanks for your slider, this is awesome!

How I can add 'disabled' class for nav buttons?
ie - in nonLoop mode, if slide is first - add class 'disabled' for PREV button. If slide is last - add class 'disabled' for NEXT button.

Thanks again! :)

Custom controls, with no custom nav, gives "TypeError: undefined is not an object"

A fairly simple CodePen:

http://codepen.io/jsit/pen/XMKzwr

var slider = tns({
    container: document.querySelector('.slider'),
    controlsContainer: document.querySelector('.controls'),
});
<div class="wrapper">
  <div class="slider">
    <img src="http://unsplash.it/600/200">
    <img src="http://unsplash.it/600/200">
    <img src="http://unsplash.it/600/200">
    <img src="http://unsplash.it/600/200">
  </div>
</div>

<!-- customized nav & dots -->
<div class="controls">
  <button>prev</button>
  <button>next</button>
</div>
<!-- Uncomment .thumbnails and it will work -->
<!--
<div class="thumbnails">
  <button></button>
  <button></button>
  <button></button>
  <button></button>
  <button>stop</button>
</div>
-->

Gives me the error "TypeError: undefined is not an object".

If I uncomment the .thumbnails div, it suddenly works.

It doesn't matter what the class is on the .thumbnails div, but it does require that there are at least as many child elements inside it as there are slides in the slider.

Also happens if you simply set controls: false.

Knowing the position of a slide in the slider

The slider when initialised duplicates slides to create a circular illusion when loop=true(I think). Because of this, there is no accurate way to know the index of the specific slide in the slider. Is there a way to know the real index of a specific slide? Or is there a possibility to add an index/position attribute?

testcafe-browser-provider-saucelabs marked as dependency?

The package testcafe-browser-provider-saucelabs is marked as a dependency when installing the package through NPM, which makes the slider install a whole lot of code (like Babel, a browser and similar stuff) I'm pretty sure I won't need. The dependency graph for my project literally (figuratively) exploded.

Shouldn't it be marked in devDependencies instead, or am I missing something?

Navigation breaks after browser resize (sometimes)

Sometimes when resizing the browser, the navigation will stop working. Sometimes I am getting this on iPad when flipping from portrait to landscape, for example.

Asking a question or submit a bug?

  • Question
  • Bug

How can others reproduce the issue?
Link or Code example:
Slider options:
slideBy: 'page', nav: false, loop: false,
items: 1

Also, my slider currently only has 2 items in it.

Tiny-slider version:
OS: Windows, iOS
Browser: Chrome, Safari

Script fails when using together with Turbolinks

Asking a question or submit a bug?

  • Question
  • Bug

How can others reproduce the issue?

// my tns function
function tinySlider() {
  const slider = tns({
    responsive: {
      '0': 1,
      '600': 2,
      '900': 3
    },
    slideBy: 1,
    autoplay: true,
    autoplayTimeout: 2500,
    autoplayHoverPause: true,
    gutter: 10,
    controlsContainer: '.slider-controls'
  });
}

// loading tns function
 window.onload = function() {
   tinySlider();
 };

// loading Turbolinks - see https://github.com/turbolinks/turbolinks
var Turbolinks = require("turbolinks");
Turbolinks.start();

// re-initiate tns function on load event
document.addEventListener("turbolinks:load", function() {
  tinySlider();
})

Tiny-slider version: 1.6.0
OS version: Fedora 26, 64bit
Browser version: FF 55, 64bit

Upon entering a page that has tiny slider, page load takes forever & eventually crashes the browser. Debugging tns points to this function:

  function getSlideEdges() {
    slideEdges = [0];
    var topFirst = slideItems[0].getBoundingClientRect()[transformAttrLegacy], attr;
    for (var i = 1; i < slideCountNew; i++) {
      // next line seems to cause the problem
      attr = slideItems[i].getBoundingClientRect()[transformAttrLegacy];
      slideEdges.push(attr - topFirst);
    }
  }

Now, I know third-party stuff is not your field, but maybe you can point me in the right direction here?

custom transition distance

Hi,
First of all thanks for this plugin.

This plugin works great. however, when using fixedWidth option where items have margins(left/right) some items are partially displayed(because of margin). When navigating the slider, the fixedWidth is used to calculate transition distance (translateX variable). An option to control the transition distance would be nice.

Thanks

Issues when importing via Browserify

I guess this is the same problem as issue #20 but since it´s close and seems to work for webbpack I wrote it a new one for browserify. The fix in #39 was working but the #41 made it throw error message again as before: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

Cange number of items with matchMedia

EDIT: Ok I feel stupid, there's a feature for that... problem solved!


Hello,

I am trying to change the number of items depending on screen width with matchMedia but I can't make it work.

Here is my code for the matchMedia:

var mqls = [
    window.matchMedia("(min-width: 650px)"),
window.matchMedia("(min-width: 1200px)")
]

function mediaqueryresponse(mql) {
if (mqls[0].matches) { 
    var nbItems = 2
} else if (mqls[1].matches) {
    var nbItems = 3
} else {
    var nbItems = 1
}
}

for (var i=0; i<mqls.length; i++) {
    mediaqueryresponse(mqls[i]),
    mqls[i].addListener(mediaqueryresponse)
}

But then I have no idea how to get it to work with tiny-slider. As there is a responsive feature, can we hook into the event listener directly?

Bug with latest version?

Since updating to the latest release I'm not able to import the module into my webpack project.

Example code:
import { tns } from "tiny-slider/src/tiny-slider.module"

Output:

application.js:15239 Uncaught ReferenceError: prop is not defined
    at whichProperty (application.js:15239)
    at Object.keys.keys (application.js:12477)
    at __webpack_require__ (application.js:677)
    at fn (application.js:88)
    at Object.<anonymous> (application.js:12176)
    at __webpack_require__ (application.js:677)
    at fn (application.js:88)
    at Object.window.KBA (application.js:10295)
    at __webpack_require__ (application.js:677)
    at fn (application.js:88)

Trace:

/***/ }),
/* 137 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = whichProperty;
function whichProperty(props) {
  var el = document.createElement('fakeelement'),
      len = props.length;
  for (var i = 0; i < props.length; i++) {
    prop = props[i];
    if (el.style[prop] !== undefined) {
      return prop;
    }
  }

  return false; // explicit for ie9-
}

Slider is not working in carousel mode

Hi,
Thanks for this plugin.
I have used it three times on one page. Items of two sliders are linked by goTo. However one of these two does not work sometimes. It is in carousel mode. The second one is always faultless. It's in gallery.

The site is: https://olga-sergeeva.com/
Tiny-slider version: 1.5.3

Multiple issues using fixedWidth: true

Asking a question or submit a bug?

  • Question
  • Bug

How can others reproduce the issue?
https://codepen.io/justindmyers/pen/WELozo

Tiny-slider version:
OS version: Windows 10 64-bit
Browser version: Chrome 60.0.3112.113

When using fixedWidth: true and not having enough items to fill the screen, a few things happen:

  • Cloned items are still displayed (i.e. a 2 slide carousel will show a full screen's width of carousel items). For my purposes, it would confuse the user to have the same items repeated over and over.
  • Using loop: false throws an error
  • Using slider.goTo("next") or slider.goTo("prev") causes the carousel to slide a seemingly random number of slides
  • Carousel doesn't start working when resizing down to the correct number of slides (nav and controls stay hidden, mouseDrag doesn't work). The opposite is also true, if you start at a low enough screen width the carousel nav and controls show and if you increase the resolution they still work.

README section 'options' as table

As proposed, I want to rework the options section as table for easier understanding and quicker overview of all features & possibilities (thus making it an enhancement of some sort), like this:

Option Type Description
fixedWidth Boolean Default: false. Controls width attribute of the slides.
items Integer Default: 1. Number of slides being displayed.
and so on ...

If I run into any problems or if I can't figure out the purpose of individual options, I'll ask you here so I can instantly include your information.

Cheers,
S1SYPHOS

[data-tns-role=nav] buttons

I noticed an issue with the nav buttons when using 7 elements within a 4 item slider. When clicking on the second nav button, the wrong button gets the aria-selected="true" attribute.

Here is a codepen to see the issue: https://codepen.io/anon/pen/OgxxdJ

To reproduce the bug (using a viewport >1200px wide):

  1. click on the second nav button
  2. notice that the button after gets the aria-selected="true" attribute

Note: This issue only exists the first time navigating the slider. Clicking on the second nav button and then the first, and then the second again seems to work just fine since the second button nicely gets the aria-selected="true" attribute.

If you would like me to submit a PR for this, please let me know and I'll do my best.

Auto height resizing

I've been testing your script and it's really great (I like when there ar not too much functions)! The only thing missing is to be able to resize the container's height based on its content. Do you plan on implementing this function?

Thanks!

Cannot read property getInfo() of undefined

This is probably user error here, but this is my code:

var slider = tns({
    container: sliderContainer,
    mouseDrag: true,
    nav: false,
    controls: false
});

console.log(slider.getInfo());

Console error on page load:
Uncaught TypeError: Cannot read property 'getInfo' of undefined

Any ideas?

Bug with mouseDrag on slide images

Asking a question or submit a bug?

  • Question
  • Bug

How can others reproduce the issue?
Live link or Code example: https://jsfiddle.net/Lak267fo/2/

I am having a strange issue across all browsers using an image with mouseDrag. If you try dragging the slider it is not as smooth and the image will stick to the mouse. It works perfectly with the demo versions using text only slides.

(Update: Everything works smoothly with background images so related to <img>)
Tiny-slider version:
OS version: MAC OS
Browser version: Safari 10.1.1

Possible to disable slider if slideCount = slideItems ?

I'm using tiny-slider with the responsive option, to display 4 items -- I wondered if it was possible to have the slider disabled if all the items are visible in the viewport?

Not that this is particularly specific to my code, here it is for reference - might help clarify too:

const newsSlider = tns({
    container: sliderContainer,
    mouseDrag: true,
    nav: false,
    gutter: 32,
    "responsive": {
        "0": 1,
        "680": 2,
        "1000": 3,
        "1300": 4
    }
})

So as there are a total of 4 items in the slider, at 1300px or higher, as the slides are all visible I want to disable the slider (ie. so mouseDrag / controls aren't visible etc). I guess ideally, it would be good to extend the responsive feature so that you can also specify other options for each breakpoint, rather than just number of slides).

Arrow keys function globally

When multiple instances of tiny-slider are on a single page with arrow-keys enabled, every slider on the page reacts to the key press.

Does 'initialized' custom event work?

Hello William,

Thanks for the great code and functionality :)

Some questions here. I try to use the initialized event but it does not fire. At the same time indexChanged event fires fine.

Can you kindly check what could be the issue? Here is my code:

        var slider3 = tns({
            container: document.querySelector('.slider-feedback'),
            axis: 'vertical',
            speed: 1600,
            items: 3,
            slideBy: 1,
            autoplay: true,
            gutter: 20,
            controlsContainer: document.querySelector('.wj-tns-controls.controls-feedback'),
            navContainer: document.querySelector('.wj-tns-thumbnails'),
        });

        // Attach the handler
        slider3.events.on('initialized', clearHiddenAttrib);

        // 
        function clearHiddenAttrib() {
            console.info('Clear hidden attribute function worked...');
        }

As I run this no initialized event fires.

If it matters:

  • I use tns-slider.js just concatenating into my RequireJS Optimizer bundle.
  • I use other 2 instances of tns slider on the same page calling them like this:
var slider = tns({
            container: document.querySelector('.slider-one'),
           // other settings
})
var slider2 = tns({
            container: document.querySelector('.slider-schedule-prices'),
            // other settings
})

Thanks for the help.

Regards,
Val

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.