Skip to content Skip to sidebar Skip to footer

How To Pause Html5 Video When Out Of View Code (non-statically Positioned)

I am using a html5 video on my website. I want it to play only when in view and pause otherwise. I am also using javascript to have a play/pause button on it. I was able to use b

Solution 1:

The code you've posted here is mostly fine and should work more or less correctly, but here are a few things to look out for:

  1. Remove the autoplay attribute completely from your video element. Setting it to "0" does not turn it off. Any value at all for autoplay will make it true.

  2. You'll probably want to call checkScroll one time at page load to cover the initial window state, in case the video is in view initially. Otherwise, it won't start until you scroll at least one time.

  3. The math here assumes that your video is positioned statically, with no parent elements that have CSS position as fixed, relative, or absolute. If you need to do that, you may need to modify the position calculation slightly. But this is not a problem in the jsfiddle you posted.

  4. Based on the value of fraction, the video will only play if 80% of it is visible. If the browser window is smaller than 80% of the area of the video element, it will never play no matter where you scroll. You may want to adjust the value compared to visible to account for that, or you can leave it as is. Up to you.

  5. Make sure the video is actually being loaded. If the file is not found or if the network is too slow, the play state may be set but you may not see it playing. You might want to have some other visual indicator of the play state, using the play and pause events and the paused property.

  6. Finally, if you're going to have a separate pause/play button, you'll want to use that to set some external variable that disables the scrolling logic so they don't conflict.

Based on your description, I suspect that you want to pay close attention to 1. and 3., as they will likely solve your problem.

Update: It looks like your problem is 3. When you have parent elements that are not positioned statically, offsetTop and offsetLeft are not sufficient to get the position of your video element within the page. You need to loop through all the ancestor elements that can affect the position, like this:

parent = video;
while (parent && parent !== document.body) {
    x += parent.offsetLeft;
    y += parent.offsetTop;
    parent = parent.offsetParent;
}

Here's a working example: http://jsbin.com/qekat/1/edit


Post a Comment for "How To Pause Html5 Video When Out Of View Code (non-statically Positioned)"