How to access Splide instances from within another function #502
-
I'm trying to mount (potentially multiple) instances of Splides like this, then set them up to be manipulated in an intersectionObserver instance. The only way I've figured out how to get the correct Splide instance is to put each instance into an array indexed by id, then call that index (as shown below). This works just fine, but it seems convoluted to me, and I assume there's a more direct way to access this (like via Splide.slides) or that I'm missing, but I just can't figure it out. Below is how I'm currently accomplishing this. Is there a better way? <script>
let $carousels = $('.section.carousel');
let carouselObserver = new IntersectionObserver((divs) => {
divs.forEach(div => {
let thisId = div.target.id;
let carousel = carousels[thisId];
let Autoplay = carousel.Components.Autoplay;
if(div.isIntersecting){
Autoplay.play();
} else if(!div.isIntersecting){
Autoplay.pause();
}
});
}, {threshold:0.6});
let carousels = [];
$carousels.each(function(i){
let carouselInstance = new Splide(this, carouselArgs).mount();
let carouselID = carouselInstance.root.id;
carousels[carouselID] = carousel;
carouselObserver.observe(this);
});
</script> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I guess you are struggling to relate elements observed by IntersectionObserver to Splide instances. The culprits that make your code much complex are jquery and iteration over the target elements twice. One solution is processing them in a single loop: Array.from( document.querySelectorAll( '.section.carousel' ) ).forEach( elm => {
const splide = new Splide( elm, { autoplay: 'pause' } ).mount();
const Autoplay = splide.Components.Autoplay;
const observer = new IntersectionObserver( ( [ entry ] ) => {
entry.isIntersecting ? Autoplay.play() : Autoplay.pause();
}, { threshold: 0.6 } );
observer.observe( elm );
} ); Note that you are using a string as an array key, but you shouldn't. carousels[carouselID] = carousel; // bad |
Beta Was this translation helpful? Give feedback.
I guess you are struggling to relate elements observed by IntersectionObserver to Splide instances. The culprits that make your code much complex are jquery and iteration over the target elements twice. One solution is processing them in a single loop:
Note that you are using a string as an array key, but you sho…