Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change attribute "autoplay" in a post

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>
like image 886
Ngo Quoc Vinh Avatar asked Dec 22 '22 19:12

Ngo Quoc Vinh


2 Answers

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>
like image 151
vadivel a Avatar answered Jan 20 '23 16:01

vadivel a


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.

like image 33
timber535 Avatar answered Jan 20 '23 14:01

timber535