sinanisler logo

Automatic Video Play/Pause Based on Visibility

This JavaScript code automatically manages the play and pause state of videos on a webpage based on their visibility.

When the webpage loads, it sets up an observer to monitor multiple videos inside elements with the class ‘.smallvideo‘. The observer uses the browser’s viewport as a reference area to determine if at least 50% of a video is visible.

<script>
  
document.addEventListener('DOMContentLoaded', (event) => {
    let options = {
        root: null, // Sets the viewport as the bounding box.
        rootMargin: '0px',
        threshold: 0.5 // 50% of the video must be visible for play/pause.
    };

    let observer = new IntersectionObserver(handleIntersection, options);

    // Select all videos within elements with the class '.smallvideo'
    let videos = document.querySelectorAll('.smallvideo video');

    videos.forEach(video => {
        observer.observe(video); // Observe each video
    });

    function handleIntersection(entries, observer) {
        entries.forEach(entry => {
            // If the video is visible in the viewport
            if (entry.isIntersecting) {
                entry.target.play(); // Play the video
            } else {
                entry.target.pause(); // Pause the video if it is not visible
            }
        });
    }
});

  
</script>
  

Leave the first comment