How To Pause Html5 Video When Out Of View Code (non-statically Positioned)
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:
Remove the
autoplay
attribute completely from your video element. Setting it to "0" does not turn it off. Any value at all forautoplay
will make it true.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.The math here assumes that your video is positioned statically, with no parent elements that have CSS position as
fixed
,relative
, orabsolute
. 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.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 tovisible
to account for that, or you can leave it as is. Up to you.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
andpause
events and thepaused
property.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)"