Q . How to play any video when it is on viewport (on screen)?

Mike Tyson. asked, Jun 08 ' 2018

How to check if any body scrolling any video which come to the screen than play with mute. 
And unmute it when gone from the screen?

  • JavaScript
  • viewport
  • video
  • autoplay

1 Answers

Use below code with view port library :

//viewport library
!function(a){function b(b){var c,d=a("<div></div>").css({width:"100%"});return b.append(d),c=b.width()-d.width(),d.remove(),c}function c(d,e){var f=d.getBoundingClientRect(),g=f.top,h=f.bottom,i=f.left,j=f.right,k=a.extend({tolerance:0,viewport:window},e),l=!1,m=k.viewport.get?k.viewport:a(k.viewport),n=m.height(),o=m.width(),p=m.get(0).toString();if(m.length||console.warn("isInViewport: The viewport selector you have provided matches no element on page."),"[object Window]"!==p&&"[object DOMWindow]"!==p){var q=m.offset();g-=q.top,h-=q.top,i-=q.left,j=i+o,c.scrollBarWidth=c.scrollBarWidth||b(m),o-=c.scrollBarWidth}return k.tolerance=Math.round(parseFloat(k.tolerance)),isNaN(k.tolerance)?k.tolerance=0:k.tolerance<0&&(k.tolerance=n+k.tolerance),Math.abs(i)>=o?l:l=k.tolerance?g<=k.tolerance&&h>=k.tolerance?!0:!1:h>0&&n>=g?!0:!1}a.fn.do=function(a){return a.apply(this),this},a.extend(a.expr[":"],{"in-viewport":function(a,b,d){if(d[3]){var e=d[3].split(",");return 1===e.length&&isNaN(e[0])&&(e[1]=e[0],e[0]=void 0),c(a,{tolerance:e[0]?e[0].trim():void 0,viewport:e[1]?e[1].trim():void 0})}return c(a)}})}(jQuery);

//jquery code to play video on scroll.
jQuery(window).scroll(function(){                           

    jQuery('iframe').each(function(i, e){
        var src = jQuery(this).attr('src');

        if(typeof src != 'undefined' && src.indexOf('/embed/') !== -1){

            var iframeContent = (e.contentWindow || e.contentDocument);
            if(iframeContent.getPlayerState() != 'playing' && jQuery(this).is(":in-viewport")){
                iframeContent.playVideo();
            } else if(iframeContent.getPlayerState() == 'playing' && jQuery(this).is(":in-viewport") == false){
                iframeContent.pauseVideo();
            }
        }
    })
});

 

Leave a Ansewer