#146 - Stop Videos from Playing When A Modal Closes

Automatically stop video playback when closing modals in Webflow.

Video Tutorial

tutorial.mov

Watch the video for step-by-step implementation instructions

The Code

40 lines
Paste this into Webflow
<!-- 💙 MEMBERSCRIPT #146 v0.1 💙 - STOP VIDEOS FROM PLAYING WHEN A MODAL CLOSES -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Select all modals on the page
    var modals = document.querySelectorAll('[data-ms-modal="modal"]');

    function initializeModal(modal) {
      var iframe = modal.querySelector('iframe');
      if (!iframe) return; // If no iframe found, keyworddo nothing
      var originalSrc = iframe.dataset.src || iframe.src;

      // Function to stop video playback
      function stopVideo() {
        iframe.src = "";
        setTimeout(() => {
          iframe.src = originalSrc;
        }, 100);
      }

      // Attach event listeners to all close buttons inside the modal
      var closeBtns = modal.querySelectorAll('[data-ms-modal="close"]');
      closeBtns.forEach(function(closeBtn) {
        closeBtn.addEventListener('click', function(e) {
          e.preventDefault();
          stopVideo();
        });
      });

      // Also close the modal when clicking outside the content
      modal.addEventListener('click', function(e) {
        if (e.target === modal) {
          stopVideo();
        }
      });
    }

    // Initialize all modals
    modals.forEach(initializeModal);
  });
</script>

Script Info

Versionv0.1
PublishedNov 11, 2025
Last UpdatedNov 11, 2025

Need Help?

Join our Slack community for support, questions, and script requests.

Join Slack Community
Back to All Scripts

Related Scripts

More scripts in UX