I have an issue, My WordPress blog embeds a video from Imgur. It autoplay when it is loaded. It also loops automatically. And it works perfectly with this embed HTML. However, it doesn't stop when we scroll it out of screen. How to stop it when scrolled out? thank
<center><video style="max-width: 100%; height: auto;" preload="auto" autoplay="autoplay" loop="loop" controls="controls" width="450" height="auto"><source src="https://i.imgur.com/84FAg6j.mp4" /></video></center>
I have just added id
to the video tag and I have just used jQuery's play and pause options based on the scroll position. Hope this will help you.
var sec_position = $('#sec').offset().top;
var vid = document.getElementById('video');
$(window).on('scroll', function() {
var window_position = window.pageYOffset;
if (sec_position < window_position) {
vid.pause();
} else {
vid.play();
}
});
#sec {
height: 500px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center><video id="video" style="max-width: 100%; height: auto;" preload="auto" autoplay="autoplay" loop="loop" controls="controls" width="450" height="auto">
<source src="https://i.imgur.com/84FAg6j.mp4" /></video></center>
<div id="sec"></div>
You can use jQuery:
HTML
adding an ID your element:
<video id="myvideo" style="max-width: 100%; height: auto;" preload="auto"
autoplay="autoplay" loop="loop" controls="controls" width="450" height="auto">
JS
calling pause on scroll
$('#myvideo').bind("ended", function(){
$('html, body').animate({
scrollTop: $(".big-div").offset().top
}, 2000);
});
function isInView(el) {
var rect = el.getBoundingClientRect();
return !(rect.top > $(window).height() || rect.bottom < 0); // visible?
}
$(document).on("scroll", function() {
$( "#myvideo" ).each(function() {
if (isInView($(this)[0])) { // visible?
if ($(this)[0].paused) $(this)[0].play(); // play if not playing
}
else {
if (!$(this)[0].paused) $(this)[0].pause(); // pause if not paused
}
});
});
CSS
.big-div{
height:1000px;
background:orange;
}
Don't forget to include jQuery before initializing the function (in the header)
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
check out my example: https://plnkr.co/edit/REanzIzi7Pb33UPHLJo9?p=preview
Scroll down and up again after some time to see the video was paused.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With