click button open WM video popup + pause video background + resume on close

<!-- Homepage - Click button pause background video -->
<script>
(function() {
  let pausedVideos = [];
  let isPopupOpen = false;
  let checkInterval = null;

  function pauseActiveVideoBackgrounds() {
    isPopupOpen = true;
    pausedVideos = [];
    
    const nativeVideos = document.querySelectorAll('.sqs-video-background-native video');
    
    nativeVideos.forEach((video) => {
      if (document.body.contains(video)) {
        const wasPlaying = !video.paused;
        pausedVideos.push({
          element: video,
          wasPlaying: wasPlaying
        });
        if (wasPlaying) {
          video.pause();
        }
      }
    });
    
    startPauseMonitor();
  }

  function startPauseMonitor() {
    if (checkInterval) {
      clearInterval(checkInterval);
    }
    
    checkInterval = setInterval(() => {
      if (!isPopupOpen) {
        clearInterval(checkInterval);
        checkInterval = null;
        return;
      }
      
      const nativeVideos = document.querySelectorAll('.sqs-video-background-native video');
      nativeVideos.forEach(video => {
        if (!video.paused) {
          video.pause();
        }
      });
    }, 100);
  }

  function resumeVideoBackgrounds() {
    isPopupOpen = false;
    
    if (checkInterval) {
      clearInterval(checkInterval);
      checkInterval = null;
    }
    
    setTimeout(() => {
      pausedVideos.forEach((videoData) => {
        const video = videoData.element;
        
        if (video && document.body.contains(video) && videoData.wasPlaying) {
          video.muted = true;
          video.play().catch(() => {});
        }
      });
      
      pausedVideos = [];
    }, 200);
  }

  document.addEventListener('wmPopup:beforeOpenPopup', function(e) {
    pausedVideos = [];
    pauseActiveVideoBackgrounds();
  });
  
  document.addEventListener('wmPopup:afterClosePopup', function(e) {
    resumeVideoBackgrounds();
  });

  const bodyObserver = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.attributeName === 'class') {
        const hasPopupClass = document.body.classList.contains('wm-popup-open');
        
        if (isPopupOpen && !hasPopupClass) {
          resumeVideoBackgrounds();
        }
        else if (!isPopupOpen && hasPopupClass) {
          pausedVideos = [];
          pauseActiveVideoBackgrounds();
        }
      }
    });
  });

  bodyObserver.observe(document.body, { attributes: true });
})();
</script>

 

Buy me a coffee