Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play HTML5 Video when scrolled to

Tags:

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?

like image 977
jp89 Avatar asked Mar 13 '13 20:03

jp89


People also ask

Why can't I display a video in HTML5?

Your browser does not support HTML5 video. To show a video in HTML, use the <video> element: Your browser does not support the video tag. The controls attribute adds video controls, like play, pause, and volume. It is a good idea to always include width and height attributes.

What is <HTML5>?

HTML5 defines DOM methods, properties, and events for the <video> element. This allows you to load, play, and pause videos, as well as setting duration and volume.

How to show a video in HTML?

To show a video in HTML, use the <video> element: Your browser does not support the video tag. The controls attribute adds video controls, like play, pause, and volume. It is a good idea to always include width and height attributes.

How do I add a JavaScript script to a video?

Start by adding a script tag underneath the video file. Since we only have a small amount of JavaScript for this technique, we'll just add it as an inline script, but you can use an external file if you prefer.


1 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.

enter image description here

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);         }); 
like image 136
Mikkel Jensen Avatar answered Jan 01 '23 20:01

Mikkel Jensen