Alistair Norris
Alistair Norris

Reputation: 67

HTML5 Video play once scrolled into view.

I've got some fullscreen video backgrounds that I want to play once they're scrolled into view.

The code I'm using for the video running is as follows.

<video id="video_background" preload="false" autoplay="false" loop="loop" volume="0"> <source src="video.webm" type="video/webm"> <source src="video.mp4" type="video/mp4"> Video not supported </video> 

The full-screen side works great, the video plays and I'm very happy with how it all looks but I've got a couple of issues.

  1. Even at the point I'm at, the video isn't taking into account the autoplay="false" attribute. It's instantly playing as soon as the page loads.

  2. Can someone point me in the right direction to play html5 video when the section is scrolled into view? I'm using sections such as the following for each bit.

<div class="container"><video id="video_background" preload="false" autoplay="false" loop="loop" volume="0"> <source src="video.webm" type="video/webm"> <source src="video.mp4" type="video/mp4"> Video not supported </video></div></section>

I can't find anything that will let me start a section when it scrolls into view.

Any ideas?

Upvotes: 0

Views: 2868

Answers (1)

aabilio
aabilio

Reputation: 1727

According to w3schools.com the autoplay must be coded just if you want autoplay, and ignore if you don't want autoplay.

To know when some element appears in the viewport yo can use jquery.appear plugin:

$('someselector').on('appear', function(event, $all_appeared_elements) {
  // this element is now inside browser viewport: play video
});
$('someselector').on('disappear', function(event, $all_disappeared_elements) {
  // this element is now outside browser viewpor: Pause/stop video?
});

If you don't want to use this jQuery plugin, in this StackOverflow question the accepted response to know where some element is scrolled into view is:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

   return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

Upvotes: 2

Related Questions