ganlanyuan / tiny-slider

Vanilla javascript slider for all purposes.
MIT License
5.24k stars 786 forks source link

Getting events to work with multiple sliders #675

Open danny-englander opened 3 years ago

danny-englander commented 3 years ago

Issue description:
Cannot get events to work with multiple sliders. I can get events to work fine with a single slider but once I do multiple, I am getting an error:

Uncaught TypeError: Cannot read property 'on' of undefined

Demo link/slider setting:

// Define all carousels
const carousel = document.querySelectorAll(".slider");

carousel.forEach((slider) => {

  tns({
    container: slider,
    items: 1,
    slideBy: "page",
    autoplay: true
  });

  const customizedFunction = function (info, eventName) {
    console.log('hello');
  }

  // Bind function to event.
  slider.events.on('transitionEnd', customizedFunction);
});

https://codepen.io/danny_englander/pen/NWbyyya

Tiny-slider version: 2.9.3

Browser name && version: Brave Version 1.20.108 Chromium: 88.0.4324.182 (Official Build) (x86_64)

OS name && version: OS X - 10.15.7

xanisu commented 3 years ago

You have to add event to current Slider object returned by tns(), not to the object your querySelector is returning.

Your code should look like this:


// Define all carousels
const carousel = document.querySelectorAll(".slider");

carousel.forEach((sliderItem) => {

  var tnsSlider = tns({
    container: sliderItem,
    items: 1,
    slideBy: "page",
    autoplay: true
  });

  const customizedFunction = function (info, eventName) {
    console.log('hello');
  }

  // Bind function to event.
  tnsSlider.events.on('transitionEnd', customizedFunction);
});