0

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!

user3766930
  • 4,929
  • 9
  • 38
  • 91

3 Answers3

4

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();
  }
});
Community
  • 1
  • 1
Schlaus
  • 15,686
  • 10
  • 31
  • 62
1

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>
Schlaus
  • 15,686
  • 10
  • 31
  • 62
Deepanshu Mishra
  • 304
  • 3
  • 15
-1

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();};
Community
  • 1
  • 1
grateful
  • 1,070
  • 11
  • 20