GIF JavaScript Video

Create Animated GIF Preview for Youtube Video Gallery

GIF (Graphic Interchange format) is the most popular image format these days which supports animation. We see gifs in social networking sites and other places where a couple of frames are quickly displayed and hence they helps in quick preview of something. Another cool usage of gifs is in Youtube. Have you ever noticed, Youtube displays a small animated preview when you hover on the static image. If you haven't, open youtube.com and hover on any image and voila…, isn't it awesome !!!

Now you may think to add these cool previews to your own video gallery and of course you won't need this when there is only one video.

GIF of Youtube Video

How to add an animated preview ?

There are two ways.

  • Create your own gif from static images (there are many online sites out there and check for some desktop based tools).
  • Use the same gifs already generated by Youtube.

In this article we will see how to use the gifs already generated by youtube and use it straight away. Lets dive deep into bit technical parts. If you inspect the elements in browser you can notice, the images quickly go away when you hover out of it. So we need a mechanism to capture the image once we hover on it. That's not all, once you get the urls you can observe they are temporary having some random tokens. So it's not a good idea to directly use them in your site. First upload them to your server and then use.

  • Open youtube.com
  • Search the video from the search bar
  • Right click on the page → Inspect → Console Tab
  • Copy and paste the below code in the console.
    var jq = document.createElement('script');
    jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(jq);
    var urls=[];
    setInterval(function(){
    	if($){
    		var url = $("#mouseover-overlay:not(:empty)").find("#thumbnail").attr('src');
    		if(urls.indexOf(url)<0){
    			var a = $("<a>").attr("href",url).attr("download", "img.png").appendTo("body");
    			a[0].click();
    			urls.push(url);
    		}
    	}
    },1000);
  • Hover on the video you need the GIF for

The GIF image will be downloaded. Now upload the image to your server.

See the below demo