how can I start playing my video in html5 when user scrolls to it?
I'm creating a webpage and I have a mp4 video there:
<video class="video--app" id="myVideo" autoplay="" muted="" preload="auto">
<source src="./img/video.mp4" type="video/mp4">
</video>
I also wrote a part of JS code:
setTimeout(function(){
document.getElementById("myVideo").play();
}, 1500);
and that works almost ok, the video starts playing after 1,5 second. But I would like to change it and start playing video when it first appears on the screen - basically when user scrolls to it. Can you give me any hint how should I modify my JS code to achieve that? Thanks!
This answer has a function for checking whether an element is in view:
function isScrolledIntoView(el) {
var elemTop = el.getBoundingClientRect().top;
var elemBottom = el.getBoundingClientRect().bottom;
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
return isVisible;
}
So after the user has scrolled, you could check if the video is in view, and if so, start it:
var videoEl = document.getElementById("myVideo");
var videoWasStarted = false;
window.addEventListener('scroll', function(e) {
if (isScrolledIntoView(videoEl) && !videoWasStarted) {
videoWasStarted = true;
videoEl.play();
}
});
Use Jquery for easability. Use Scroll Function so that when user comes Scrolling to your Video it will trigger the video to Play.
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
if(wScroll > $('#myVideo').offset().top - ($(window).height() / 1.2)) {
$('#myVideo').get(0).play()
}
});
Remember to add jquery library in your HTML
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
You could include jQuery to make life easier for you. My suggestion is adapted from this post: check-if-element-is-visible-on-screen
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
if(isOnScreen($('#myVideo'))) { $('#myVideo').play();};
链接地址: http://www.djcxy.com/p/83612.html
上一篇: 设置SVG从滚动开始