Search code examples
javascriptvideohtml5-videoswiper.js

Pause video when not in view swiper.js


I recently started using javascript swiper - https://swiperjs.com. I made the slides to contain html videos. The problem is that if I play a video and then swipe for another slide it (logically) keeps playing in the background and I felt it is a bit annoying. How should I make the videos pause when they’re not in view?

Basic call of the swiper -

// SWIPER SERVICES START
if (document.body.id === "services") {
  const swiper = new Swiper(".swiper", {
    loop: true,
    speed: 600,
    autoplay: {
      delay: 15000,
    },
    // Optional parameters
    direction: "horizontal",
    loop: true,
    // If we need pagination
    pagination: {
      el: ".swiper-pagination",
    },
    // Navigation arrows
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    // And if we need scrollbar
    scrollbar: {
      el: ".swiper-scrollbar",
    },
  });
}
// SWIPER SERVICES END

Slides looking like this

 <div class="swiper-slide">
      <p class="note date">2023</p>
      <p class="note">
        <a
          href="https://video.dk/“
          target="_blank"
          rel="noopener noreferrer"
          ><span>Showreel</span
          ><span
            >&nbsp;<i class="fa-solid fa-arrow-up-right-from-square"></i
          ></span>
        </a>
      </p>
      <video
        src="/img/showreel.mp4"
        preload="metadata"
        controls="controls"
        playsinline
        role="video"
        aria-label=“label”
        aria-describedby="<?php echo $lang['asset_40'] ?>"
        poster="/img/cover"
      ></video>
    </div>

I'm looking forward to read your meaningful non toxic input. Cheers


Solution

  • There is an event slideChange that you can listen for and pause the video accordingly.

    Here is a modified version of your code :

    // SWIPER SERVICES START
    if (document.body.id === "services") {
      const swiper = new Swiper(".swiper", {
        loop: true,
        speed: 600,
        autoplay: {
          delay: 15000,
        },
        direction: "horizontal",
        loop: true,
        pagination: {
          el: ".swiper-pagination",
        },
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
        scrollbar: {
          el: ".swiper-scrollbar",
        },
        on: {
          slideChange: function () {
            // Pause videos in the previous slide
            const previousSlide = this.slides[this.previousIndex];
            pauseVideosInSlide(previousSlide);
          },
        },
      });
    }
    
    // Function to pause all videos in a given slide
    function pauseVideosInSlide(slide) {
      const videos = slide.querySelectorAll('video');
      videos.forEach(video => {
        if (!video.paused) {
          video.pause();
        }
      });
    }