简体   繁体   中英

Auto pause/play on scroll Javascript autoplay video html5

I am attempting to create a video gallery on html5 with JS. I have it where you can scroll left to right between muted autoplay html5 videos and the videos will play/pause when scrolled onto/away from. This works fine.

Code Pen

The problem I am running into is when a user adjusts any of the html5 controls the autopause on scroll will no longer work. I am ok with turning off user video controls but I still need a way to toggle audio on/off. I added a button for it, but even when a user toggles the audio from the button, the on scroll pause/play JS stops working.

Hopefully, this makes sense. I appreciate any help!

the autoplay/pause Jquery I have:

$(window).scroll(function(){
  var scroll = $(this).scrollTop();
  scroll > 300 ? myvid.pause() : myvid.play()
}) ```

I found the answer in other question and it's work for me:

How to play pause video on scroll

As DaniP said before:

You need to bind your function to the scroll event and also change from autoplay to actually play() - pause() , check this example snippet:

Note: I have changed from 300 to 70 just for the example but you can keep your breakpoint as you want

 var myvid = $('#myVid')[0]; $(window).scroll(function(){ var scroll = $(this).scrollTop(); scroll > 70 ? myvid.pause() : myvid.play() })
 body { background:#e1e1e1; height:1000px; } video { display:block; width:300px; margin:0 auto; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <video id="myVid" width="100%" controls autoplay> <source type="video/mp4" src="http://html5demos.com/assets/dizzy.mp4"> </video>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM