0
votes

I have a non-autoplaying slick slider with images and HTML5 videos. My goal is to play the video, if the current slide is a video.

If the user swipes to the next slide, the currently playing video should be paused.

If the next slide is a video, this video should start playing.

My following code is working, but only for the first video in a slider. All following videos seem to ignore the play function, even though the console logs are correct.

    //  PLAY IF FIRST SLIDE IS VIDEO
    $('.bs-swiper').on('init', function(event, slick){
        if ($('.slick-current .bs-item figure').hasClass('bs-video')) {
            $('video.bs-media')[0].play();
            console.log('play if first slide is a video!');
        }
    });

    //  PLAY/PAUSE IF VIDEO
    $('.bs-swiper').on('afterChange', function(event, slick, currentSlide, nextSlide){
        if ($('.slick-current .bs-item figure').hasClass('bs-video')) {
            $('video.bs-media')[0].play();
            console.log('play this video slide!');
        }
    });

    $('.bs-swiper').on('beforeChange', function(event, slick, currentSlide, nextSlide){
        if ($('.slick-current .bs-item figure').hasClass('bs-video')) {
            $('video.bs-media')[0].pause();
            console.log('pause this video slide!');
        }
    });

As I'm no javascript-pro it would be great if someone could help to adjust my code, so every video element in the slider get's played if it is the current slide. Right now, only the first video in the slider gets played. All other videos in the slider don't get started, even though the console logs fire correctly.

Thank you very much for your help in advance!

1
Based on your code it looks like you are referring to the first video everywhere $('video.bs-media')[0]. You should change the iterator based on the current slide. - Besat
Thank you very much for your comment! I actually want the play/pause function to only execute on the current/first video. Your comment made me try to add the .slick-current class to the video object like this $('.slick-current video.bs-media')[0].play(); and now everything is working as required! Thank you for your input! - ic7

1 Answers

0
votes

I realized I had to also add the '.slick-current' class to the video object like this $('.slick-current video.bs-media')[0].play(); - now all video slides start to play when they are "in view" and get paused when they are not. Woohoo!