video's audio continues playing even after modal is closed (not using iframe)

Posted by DiamondKing__@reddit | learnprogramming | View on Reddit | 3 comments

I'm out of ideas,, for context im just a very beginner programmer (student actually,, just an elective for html and css only),, so javascript aint really up my alley on this so im asking for help cuz i really dont get why it isnt working.

As the title says, when I close the modal of the video, the audio keeps playing. I have searched a lot of solutions and i might not be doing it right. The code i'm using for the modal aint mine, it was mainly used for image modals and thought to use the same line of codes for videos but ig it doesnt work that easily.

Here is the gist of my html code for each of the modal, i'll just show two of em but i hope yall will get the idea

<div id="modal1" class="modal">
        <span class="close" onclick="closeModal('modal1')">&times;</span>
          <video class="modal-content" controls>
            <source src="" type="video/mp4">
          </video>
      </div>

<div id="modal2" class="modal">
        <span class="close" onclick="closeModal('modal2')">&times;</span>
        <video class="modal-content" controls>
            <source src="" type="video/mp4">
        </video>
      </div>

Then here is the script part

<script>
      function openModal(modalId) {
        let modal = document.getElementById(modalId);
        modal.style.display = "flex";
        modal.classList.add("show");
      }

      function closeModal(modalId) {
        let modal = document.getElementById(modalId);
            modal.classList.remove("show");
            setTimeout(function () {
              modal.style.display = "none";
            }, 300);

        let vid = document.querySelector('.modal-content');

        vid.pause();
        vid.currentTime = 0;   
        }
</script>

im not sure of what else i needed to show to come up with a solution, but if you do find one, i'd appreciate a bit of explanation as well so I could understand and learn it better! In a very basic terms hopefully,, I didn't think wanting something pop up would need javascript so i really just dipped myself into something more complicated than i thought.