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.

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) {
      ; // Play the video
            } else {
      ; // Pause the video if it is not visible


Leave the first comment