Instagram Like Auto Play Pause videos when visible using JavaScript

Instagram Like Auto Play Pause videos when visible using JavaScript

Auto-play videos are a very cool feature for a web application. Like Instagram or facebook, they already had that feature implemented in their web application. with this feature, a user can see videos without click on anything in a video player. also, we can set the flag to ON or OFF to enable autoplay feature.
To implement this feature we have used VisSense.js library to make our work easy and quick. although it has much-extended functionalities to support our app videos.

DEMODOWNLOAD

What we are going to build?

Autoplay Video Screen
Autoplay Video Screen

We are going to create a web application in which will have multiple videos and it should play the video automatically. also, have toggle checkbox to on or off auto-play videos. so it will play the video automatically when a screen is visible and pause when hidden.

Prerequisites

For creating autoplay video app you need following things.

1) VisSense.js : Download Here
2) JQuery (Optional) : Or else you can use javascript.

Getting Started

Let’s start with adding VisSense script to main index.html file and other library like Bootstrap, JQuery and app.js which contain our custom code related to functionality as follows,

Head Links & Scripts

  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="lib/bootstrap/bootstrap.min.js"></script>
  <script src="lib/vissense.min.js"></script>
  <script src="app/app.js"></script>

And then will add multiple videos in body with some dummy content so that we can scroll and see videos in actions. you can find index.html file here.

Auto-play Full Functionalities

Now, will go through our main functionality which plays videos automatically. so let’s see below code first,

app/app.js
$(document).ready(function(){
    $("#autoplaySelection").prop("checked", true); // Initially set to autoplay on
    var videos = $('video'), // All videos element
        allVidoesVisenseObj = [];
    var monitorVideo = function(video){ //Handler for each video element
        var visibility = VisSense(video, { fullyvisible: 0.75 }),
            visibility_monitor = visibility.monitor({
                fullyvisible: function(e) {
                    video.play();
                },
                hidden: function(e) {
                    video.pause();
                }
            }).start();
        return {
            visMonitor : visibility_monitor,
            monitorStop : function(){
                this.visMonitor.stop();
            },
            monitorStart : function(){
                this.visMonitor.start();
            }
        };
    };
    videos.each(function( index ) {
        var monitorVids = monitorVideo(this);
        allVidoesVisenseObj.push(monitorVids);
    });
    $("#autoplaySelection").change(function(){ // On change element for on/off autoplay Videos
        var checkedCond = $(this).is(":checked");
        if(checkedCond){
            $.each(allVidoesVisenseObj, function(index, value){
                value.monitorStart();
            });
        }else{
            $.each(allVidoesVisenseObj, function(index, value){
                value.monitorStop();
            });
        }
    });
});

In above code, will first set the checkbox to ON for play all videos initially when a screen is visible.
and then will select all the video element in one variable (i.e : videos).
allVideosVisenseobj array in which will store all the VisSense object functionality for further handling.

in monitorVideo function first will initiate the VisSense function which is going to accept the two params first is video element and another is options ( i.e: VisSense(video, { fullyvisible: 0.75}) ) and then will monitoring all videos with its individual functionality. here how we monitoring as shown below,

VisSense.js API

var video = $('#video');
var visibility = VisSense(video[0], { fullyvisible: 0.75 });
var visibility_monitor = visibility.monitor({
  fullyvisible: function() {
    video.play();
  },
  hidden: function() {
    video.stop();
  }
}).start();

In monitor, there are couple of more options in which you can detect following things,

VisSense Monitor options

  • strategy : a strategy (or array of strategies) for observing the element. VisSense comes with two predefined strategies. See below
  • start : function to run when monitoring the element starts
  • stop : function to run when monitoring the element stops
  • update : function to run when elements update function is called
  • hidden : function to run when element becomes hidden
  • visible : function to run when element becomes visible
  • fullyvisible : function to run when element becomes fully visible
  • visibilitychange : function to run when the visibility of the element changes
  • percentagechange : function to run when the percentage of the element changes
  • async : a boolean flag indicating whether events are synchronous or asynchronous

For more detailed information about options you can visit its official document here as VisSense.js Documentation.

Further will call monitorVideo function for all existing video element which is present on the screen.

ON/OFF Auto-play

also, will add functionality related to autoplay ON/OFF. in which based on checkbox checked or unchecked we are going to call stop or start monitoring video function as shown below,

    $("#autoplaySelection").change(function(){ // On change element for on/off autoplay Videos
        var checkedCond = $(this).is(":checked");
        if(checkedCond){
            $.each(allVidoesVisenseObj, function(index, value){
                value.monitorStart();
            });
        }else{
            $.each(allVidoesVisenseObj, function(index, value){
                value.monitorStop();
            });
        }
    });

Conclusion

Auto-play feature is cool in terms of user accessibility and interaction with the user interface. so that user doesn’t need to click on the screen to play videos. and with the help of VisSense.js, it gives us more flexibility to interact with video element and extend our feature more user-friendly.

Like our articles? Get them straight to your inbox!

* indicates required
Instagram Like Auto Play Pause videos when visible using JavaScript
Tagged on:             

One thought on “Instagram Like Auto Play Pause videos when visible using JavaScript

  • January 9, 2017 at 4:55 pm
    Permalink

    thank you so much, that is what i need for my project.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *