vue-slick-carousel
vue-slick-carousel copied to clipboard
<video> tag Autoplay/manual play() function not working inside the carousel if videos are out of Viewport.
Framework : NUXT SSR.
Explanation: We need to play the videos inside the carousel component. As the user will click on next/prev button of carousel or click on the video itself, the video should play and stop if clicked again on the video. Since we should have multiple videos on the viewport at once and centered also, we're using centerMode true as suggested in the library and providing the below options.
slickOptions: { initialSlide: 0, slidesToShow: 5, slidesToScroll: 1, centerMode: true, arrows: false, infinite: true, swipe: false, autoplay: false, },
Issue: If the videos are less and inside the viewport, videos are playing correctly. If the videos are more, the carousel might be adjusting the videos outside the viewport. In that case, only video's audio is playing not the video. And it is lagging also.
I checked an example online for this: https://codesandbox.io/s/brave-sky-ts09p?file=/src/components/HelloWorld.vue. We can see even in the above example if we click the indicators one after the other, the 4th video's sound is playing only not the video. Mine have a use-case of multiple videos in single view which we can do with slidesToShow option.
Here is the full code example:
<template>
<vue-slick-carousel v-bind="slickOptions">
<div
v-for="(item, index) in someArray"
:key="${index}-carousel"
>
<video
:src="item.src"
playsinline
:id="`video${index}"
@click="(e) => changeAutoplayIndex(index, e)"
></video>
</div>
</vue-slick-carousel>
</template>
<script>
data() {
return {
slickOptions: {
initialSlide: 0,
slidesToShow: 5,
slidesToScroll: 1,
centerMode: true,
arrows: false,
infinite: true,
swipe: false,
autoplay: false,
}}
}
methods:{
changeAutoplayIndex(index, e) {
setTimeout(() => {
const lastAutoPlayVideo = document.querySelector('#video${this.autoplayIndex}')
const currentVideo = document.querySelector('#video${index}')
if (this.autoplayIndex !== null && this.autoplayIndex === index) {
lastAutoPlayVideo.pause()
} else if (this.autoplayIndex !== null) {
lastAutoPlayVideo.pause() // pausing the previous video
currentVideo.currentTime = 0
currentVideo.play() // starting new video that was clicked.
} else {
currentVideo.currentTime = 0
currentVideo.play()
}
this.autoplayIndex = index
}, 200)
}
}
Please help us here. Thanks in advance.