Skip to content

Autoplay/pause videos when in/out of viewport #15

Description

@niklasquitzau

Is it possible to have the video backgrounds autopause, when scrolled past them and to only play, when they are visible in the window? I two video background sections on one page, and the first video, which is all the way in the top as a banner, is working fine and stops at the right time when I scroll past it but the other video further down also plays/pauses according to the first video in the top.

I have used this script:

var videos = document.getElementsByTagName("video"),
        fraction = 0.8;
        function checkScroll() {

            for(var i = 0; i < videos.length; i++) {

                var video = videos[i];

                var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
                    b = y + h, //bottom
                    visibleX, visibleY, visible;

                    visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                    visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));

                    visible = visibleX * visibleY / (w * h);

                    if (visible > fraction) {
                        video.play();
                    } else {
                        video.pause();
                    }

            }

        }

        window.addEventListener('scroll', checkScroll, false);
        window.addEventListener('resize', checkScroll, false);

Thanks :)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions