I need help with a particular bit of JS I'm using to make HTML5 videos play when in view.
The code:
$(document).ready(function() {
// Get media - with autoplay disabled (audio or video)
var media = $('#video1, #video2, #video3, #video4, #video5');
var tolerancePixel = 10;
function checkMedia(){
// Get current browser top and bottom
var scrollTop = $(window).scrollTop() + tolerancePixel;
var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel;
//if ($(window).scrollTop() > $(window).height() - 100) {
media.each(function(index, el) {
var yTopMedia = $(this).offset().top;
var yBottomMedia = $(this).height() + yTopMedia;
if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){
$(this).get(0).play();
} else {
$(this).get(0).pause();
}
});
//}
}
$(document).on('scroll', checkMedia);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:500px"></div>
<video muted id="video4" class="lightbulbs" width="100%" height="auto">
<source src="http://www.ddi.com.au/culture/img/lightbulbs.mp4" type="video/mp4">
</video>
<div style="height:500px"></div>
I obtained this code from this answer: https://stackoverflow.com/a/26508106/10213848
My issue is that once the video is finished, it can be triggered again by scrolling upward. I need the video/s to only play once and not get triggered again.
Any help would be greatly appreciated.