Automatically play html video when in element becomes visible in viewport

Actually I just want to put this as a kind of Wiki, after breaking my fingers on this.

  1. How to automatically start video when in viewport.
  2. Most importantly: WordPress compatible solution PURE JavaScript. No JQuery. Why? Because newbies like me have a hard time “enqueing” libraries into wordpress… When even just receiving a scroll event is hard…

Anyway, posting answer below:

Related posts

1 comment

  1. So – A straight forward, shortest solution is for creating a video on an html page, or indeed use a “raw HTML” element in WordPress:

    <script type="text/javascript">
    
      var video = null;
      var ended = false;
    
      function checkScroll()
      {
        if( video == null )
          return;
        var rect = video.getBoundingClientRect();
        // console.log( rect.top, rect.bottom, window.innerHeight, document.documentElement.clientHeight );
        var inViewPort = Math.abs( rect.top ) < window.innerHeight;
        if( inViewPort )
        {
          if( video.paused && ( ended == false ) )
          {
            video.play();
            video.addEventListener( 'ended', myHandler, false );
            function myHandler(e)
            {
              ended = true;
            }
          }
        }
        else
        {
          video.currentTime = 0;
          ended = false;
        }
      }
    
      window.onload = function()
      {
        video = document.getElementById( 'rubi-second-video' );
        window.onscroll = function()
        {
          checkScroll();
        }
      }
    
      checkScroll();
    

Comments are closed.