user3766930 user3766930 - 4 months ago 7x
Javascript Question

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">

I also wrote a part of JS code:

}, 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?


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;;