Benjamin Tinker Team : Web Development

YouTube and Vimeo Background Images

Benjamin Tinker Team : Web Development

When including YouTube and Vimeo videos on a website it may be required to render a preview image of the video. Clicking the preview can then show the video in a pop-up window for the user to watch at their lesure. Here are 2 code snippets that using YouTube and Viostreams own API to get thumbnails of videos hosted on their servers.

YouTube

Each YouTube video has its own unique video Id that can be taken from the URL of the video. Using this video Id you are able to grab the default thumbnail and paste it on your site with the following code. Substitute [VIDEO_ID] with the unique video Id from the YouTube URL.

<img class="MyVideo" src="http://img.youtube.com/vi/[VIDEO_ID]/hqdefault.jpg" alt="" data-url="http://youtube.com.au/watch?v=[VIDEO_ID]">

Vimeo

Vimeo also has unique video Id numbers for all of its media content. You can access their public API to gather the URL of the default thumbnail. Using the following code will render a thumbnail on screen for your Vimeo media.

<img class="MyVideo" src="/blank.png" alt="" data-videoId="[VIDEO_ID]" data-url="http://vimeo.com/[VIDEO_ID]">

 

$(document.ready(function(){
 var videos = $('.MyVideo');
  if (videos.length>0)
  {
   $.each(videos,function(index){
    var videoId = $(videos[index]).data('videoId');
    if (videoId!=null)
    {
      $.getJSON(
       'http://vimeo.com/api/v2/video/' + videoId + '.json',
        function (data) {
          $(videos[index]).attr('alt', data[0].thumbnail_large).attr('src', data[0].thumbnail_large);
      });
     }
   });
 }
});

Above we are looping through all instances of images with the MyVideo class. We check if they have a videoId data property and use that to call the Vimeo API which returns a JSON object. The JSON object is then parsed to gather the details of the thumbnail image.

Show the Video in a Pop-up

Using Magnific Popup JQuery library we can hook up our above images to load the relative video when clicking the image.

$(document).ready(function(){
 $('.MyVideo').click(function (e) {
   var link = $(this);
   $.magnificPopup.open({
     items: {
     src: $(link).data('url'),
     type: 'iframe'
   }
  });
 });
});

With these techniques you can easily have previews of videos from YouTube and Vimeo on your site for viewing. It takes out the load time of having iframes embedded in your content and gives the oportunity to show the videos at full size and still within the boundaries of your website. All of these clicks can then be tracked for impressions too and any other functionality you require.