Splidejs / splide

Splide is a lightweight, flexible and accessible slider/carousel written in TypeScript. No dependencies, no Lighthouse errors.
https://splidejs.com
MIT License
4.89k stars 424 forks source link

Multiple Splide Instances - move event - incorrect instance in event #1231

Closed cheeseytoastie closed 2 months ago

cheeseytoastie commented 1 year ago

Checks

Version

v4.1.4

Description

Creating multiple instances in a loop and hooking onto the move event.

In the example below the event of the first slider is raised but the pagination object passed to my custom function has the second splide instance (can be see in which "dot" has the active class added).

https://codepen.io/siempre_steve/pen/oNyyrMo

Reproduction Link

https://codepen.io/siempre_steve/pen/oNyyrMo

Steps to Reproduce

  1. Click / swipe slides in the top slider
  2. See how the pagination dot in slider two is the one that gets the active class.

Expected Behaviour

Would expect paginationDots in the below code to be the correct instance not the last splide created.

splide.on('move', function (data, i) { var paginationDots = splide.Components.Pagination.items; updateSplideThreeDotPagination(paginationDots, data); });

cheeseytoastie commented 1 year ago

I can see that I could have done var paginationDots = splideInstances[0].Components.Pagination.items;

The missing bit here is how to know what the index to pass into the splideInstances would be?! The event doesn't pass in the instance (from what I can see?!?).

If the events were passed the id of the splide element that caused the event I think we could search instances for that id.

carasmo commented 9 months ago

Yes, that's the expected behavior. You need to use forEach to mount, see working example:

https://codepen.io/carasmo/pen/LYaQZBz/f91cced2ccbf58b0ae1fa1bff3c65397

document.addEventListener( 'DOMContentLoaded', function() {

const service_related_slider = [...document.querySelectorAll('.splide')];

service_related_slider.forEach(splide => {
new Splide(splide, {
    type: 'slide',
    autoplay: false,
    rewind: true,
    pagination: true,
    arrows: true,
      }).mount();
});

} ); 
cheeseytoastie commented 2 months ago

Yes, that's the expected behavior. You need to use forEach to mount, see working example:

https://codepen.io/carasmo/pen/LYaQZBz/f91cced2ccbf58b0ae1fa1bff3c65397

document.addEventListener( 'DOMContentLoaded', function() {

const service_related_slider = [...document.querySelectorAll('.splide')];

service_related_slider.forEach(splide => {
new Splide(splide, {
      type: 'slide',
      autoplay: false,
      rewind: true,
      pagination: true,
      arrows: true,
      }).mount();
});

} ); 

Sorry - I didn't get the notification on this. Amazing - thanks so much for showing the right way to do this. Sorry the thanks took 8 months.