Search code examples
javascripthtmlvideopause

How to make an HTML video pause playing when switching to next video in gallery


I need help figuring out how to make an html video stop playing when I click on the previous/next arrow and I'm all out of ideas at this point. I have a simple video gallery that works fine except for the fact that when I select next or previous the current video will continue to play and the audios between the new video and previous video will start to overlap each other. Any ideas on how I can fix this issue? Thanks

This is the code I'm using below and didn't include any of my attempts at getting the video to pause:

<div class="vidContainer">
  <div class="myVideos">
      <video src="images/Videography/Cali/P1010538.MP4" controls style="width:100%">
  </div>
  <div class="myVideos">
      <video src="images/Videography/Cali/P1010540.MP4" controls style="width:100%">
  </div>
  <div class="myVideos">
      <video src="images/Videography/Cali/P1010541.MP4" controls style="width:100%">
  </div>
  <div class="myVideos">
      <video src="images/Videography/Cali/P1010543.MP4" controls style="width:100%">
  </div>
</div>

  <a class="prev" onclick="plusSlides(-1)">❮</a>
  <a class="next" onclick="plusSlides(1)">❯</a>

<script>
var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("myVideos");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  slides[slideIndex-1].style.display = "block";
}
</script>

Solution

  • This is because you just set the display none for all the other videos and not pause them before switching.

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("myVideos");
      if (n > slides.length) {slideIndex = 1}
      if (n < 1) {slideIndex = slides.length}
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";
          slides[i].querySelector("video").pause()
      }
      slides[slideIndex-1].style.display = "block";
    }
    

    This should do the trick, which pauses the video element inside each myVideo instance.