Sunday, July 20, 2014

Embedding youtube (or vimeo) video on website.



I'll show you how to easily embed YouTube or Vimeo video on your site. I use this method to convert user added youtube links into player, so that users doesn't have to leave site to see it.




In order to display player on a site will have to convert regular youtube link:

https://www.youtube.com/watch?v=w08pX3FX9Hs

To embeded version:

https://www.youtube.com/embed/w08pX3FX9Hs

And place it inside IFrame. What's more I want the IFrame to fit page width and display player as big as possible.

1. Wrap places where you expect video link to appear, ie:

 <span><!-- link to video --></span>  


2. Add JS function to convert links and embed them in IFrames:

 function embedVideos() {  
  $('*:contains("youtu")').each(  
   function(el){  
    if($(this).children().length < 1)  
    {  
     //youtube, get video id ([^&]+ -> match any character apart from &, as it will be a next url parameter)  
     var iframeToEmbed = $(this).text().replace(/(?:http.*:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|v\/)?([^&\s\?]+)(.+)?/g, '<div class="videoWrapper"><iframe src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></div>');  
     $(this).html(iframeToEmbed);  
    }  
   });  
  $('*:contains("vimeo")').each(  
   function(el){  
    if($(this).children().length < 1)  
    {  
     var iframeToEmbed = $(this).text().replace(/(?:http.*:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<div class="videoWrapper"><iframe src="https://player.vimeo.com/video/$1" frameborder="0" allowfullscreen></iframe></div>');  
     $(this).html(iframeToEmbed);  
    }  
   });  
 }  

Remember to call this function, best after page load:

 $(document).ready(function(){  
    //....  
    embedVideos();  
 });  

3. All that remains is to style IFrame so it takes all available place. Add following styles to your site:

 .videoWrapper {  
  position: relative;  
 }  

 .videoWrapper iframe {  
  position: absolute;  
  top: 0;  
  left: 0;  
  width: 100%;  
  height: 100%;  
 }  

And that's it! Let me know if you find it helpful or there is a better way;)

No comments:

Post a Comment