0

I need to insert in my Wordpress page a video uploaded in Media Library. This video has to autoplay when is in browser view and has to stop on user scroll.

I tried to use tag with autoplay function and it's ok. Then I have add to my js folder (in theme folder) a file with some Javascript code in order to add stop on scroll function. I suspect that the code I have tried if fine only with YouTube link.

This is the code I have tried

//play when video is visible
var videos = document.getElementsByTagName("iframe"), fraction = 0.8;

function checkScroll() {

  for(var i = 0; i < videos.length; i++) {
    var video = videos[i];

    var x = 0,
        y = 0,
        w = video.width,
        h = video.height,
        r, //right
        b, //bottom 
        visibleX, visibleY, visible,
        parent;


    parent = video;
    while (parent && parent !== document.body) {
      x += parent.offsetLeft;
      y += parent.offsetTop;
      parent = parent.offsetParent;
    }

    r = x + parseInt(w);
    b = y + parseInt(h);


    visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
    visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));


    visible = visibleX * visibleY / (w * h);


    if (visible > fraction) {
      playVideo();
    } else {
      pauseVideo();

    }
  }

};


var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
};

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);

    //check at least once so you don't have to wait for scrolling for the    video to start
    window.addEventListener('load', checkScroll, false);
};


function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
      //console.log("event played");
    } else {
      //console.log("event paused");
    }
};

function stopVideo() {
    player.stopVideo();
};

function playVideo() {
  player.playVideo();
};

function pauseVideo() {
  player.pauseVideo();
};

Using a Youtube link the script pause video on scroll but don't autoplay. I expect both autoplay and pause on scroll using a video from my Wordpress media library

3 Answers3

0

var autoPlayVideo = document.getElementById("ocScreencapVideo");
    autoPlayVideo.oncanplaythrough = function() {
        autoPlayVideo.muted = true;
        autoPlayVideo.play();
        autoPlayVideo.pause();
        autoPlayVideo.play();
    }
<video id="ocScreencapVideo" autoplay="autoplay" muted="muted" loop="loop" playsinline="playsinline" preload="metadata" data-aos="fade-up">
  <source src="https://www.youtube.com/watch?v=W6NZfCO5SIk">
    Your browser does not support MP4 Format videos or HTML5 Video.
</video>
0

Add this custom script to your wordpress. You can use plugins like Simple Custom CSS and JS for adding custom snippets.

Here the function checkVisible is taken from another answer here.

jQuery(document).ready(function ($) {

    //To check if element is visible
    function checkVisible(elm) {
        var rect = elm.getBoundingClientRect();
        var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
        return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
    }
    
    //To play-pause self-hosted videos in elementor only when it's visible
    $(window).scroll(function () {
        $(".elementor-video").each(function (i, obj) {
            if (checkVisible(obj)) {
                obj.play();
            } else
                obj.pause();
        });
    });
});
-1

Rather than using a custom script, you can go with this [plugin][1] provided by Wordpress library to save time and efforts.

Another solution is to use this javascript for autoplay video:

https://codepen.io/bloodcrow777/pen/QBVKKy

var autoPlayVideo = document.getElementById("ocScreencapVideo");
    autoPlayVideo.oncanplaythrough = function() {
        autoPlayVideo.muted = true;
        autoPlayVideo.play();
        autoPlayVideo.pause();
        autoPlayVideo.play();
    }
<video id="ocScreencapVideo" autoplay="autoplay" muted="muted" loop="loop" playsinline="playsinline" preload="metadata" data-aos="fade-up">
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"
          type="video/mp4">
    Your browser does not support MP4 Format videos or HTML5 Video.
</video>
Jinal Dabhi
  • 181
  • 1
  • 2
  • 13