Play HTML5 Video when scrolled to

Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?

Answers


In brief

Let's say our browser window W currently scrolled to y-position scrollTop and scrollBottom

Our video will NOT be played when its position is at V1 or V2 as below snapshot.

Code details

        $(document).ready(function() {
            // Get media - with autoplay disabled (audio or video)
            var media = $('video').not("[autoplay='autoplay']");
            var tolerancePixel = 40;

            function checkMedia(){
                // Get current browser top and bottom
                var scrollTop = $(window).scrollTop() + tolerancePixel;
                var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel;

                media.each(function(index, el) {
                    var yTopMedia = $(this).offset().top;
                    var yBottomMedia = $(this).height() + yTopMedia;

                    if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){ //view explaination in `In brief` section above
                        $(this).get(0).play();
                    } else {
                        $(this).get(0).pause();
                    }
                });

                //}
            }
            $(document).on('scroll', checkMedia);
        });

hope this helps but it has been answered before

http://jsfiddle.net/jAsDJ/

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);

You can use window.pageXOffset and window.pageYOffset to check how far your browser window is scrolled both vertically and horizontally. Use these with window.innerWidth and innerHeight and some basic geometry math to calculate how much your visible page overlaps with the video itself. Put this all in a function that you can attach to the scroll and resize event on the window object to run the check every time the scrolling changes.

Here is some sample code:

var video = document.getElementById('video'),
    info = document.getElementById('info'),
    fraction = 0.8;

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

  if (window.pageXOffset >= r ||
      window.pageYOffset >= b ||
      window.pageXOffset + window.innerWidth < x ||
      window.pageYOffset + window.innerHeight < y
     ) {    

    info.innerHTML = '0%';
    return;
  }

  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);

  info.innerHTML = Math.round(visible * 100) + '%';

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

}

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

//one time at the beginning, in case it starts in view
checkScroll();

//as soon as we know the video dimensions
video.addEventListener('loadedmetadata', checkScroll, false);

And a working example.

This code assumes a pretty simple page layout. If your video is positioned absolutely inside another element that has "position: relative" set, then you'll need to do a little more work to calculate the correct position of the video. (The same goes if the video has been moved with CSS transforms.)


There is a new API for this scenario, called Intersection_Observer_API, which Chrome 51+ and Edge 15+ has supported.

var options = {
    root: document.querySelector('.scroll-container'),
    rootMargin: '0px',
    threshold: 1.0 // trigger only when element comes into view completely
};
var ob = new IntersectionObserver((entries, observer) => {
    entries[0].target.classList.toggle('red');
}, options);

// observe all targets, when coming into view, change color
document.querySelectorAll('.target').forEach((item) => {
    ob.observe(item);
});

Here is a simple demo: https://codepen.io/hectorguo/pen/ybOKEJ


Need Your Help

HTTP basic auth for Capybara

ruby-on-rails testing authentication webrat capybara

I'm writing some RSpec tests for my Rails 3 application and trying to switch from Webrat to Capybara. So far so good but the application uses HTTP basic auth to authorize my admin user, any idea ho...

Android: give a webview rounded corners?

java android rounded-corners

I'm trying to give my webView rounded corners.