Create Embed Video from Youtube Link and Make It Responsive

It is easier to create an Youtube embed video by using the pre-amde code supplied by Youtube. Under a video, you click on “Share” then “Embed”. There will be an iframe code which can be pasted in any sites which support HTML.

However, this post wants to introduce a way for those, mostly for developers, who want to display embedded video only after a user clicks on a link or any button. Furthermore, we want to make the video player responsive as well.

HTML

We will create a link for click event and a wrapper to display video player.

<a href="https://www.youtube.com/watch?v=JGwWNGJdvx8" class="video-link">Open this video</a>

<div id="video-player"></div>

A responsive Youtube video

Javascript

jQuery(document).ready(function(){
    jQuery('.video-link').on('click', function(e){
	var url = jQuery(this).attr('href');
	var video_id = new RegExp('[\\?&]v=([^&#]*)').exec(url);
	var embed_url = '';
        if (video_id && video_id[1]) {
            embed_url = 'http://youtube.com/embed/' + video_id[1];
        }
        var embed_code = '<iframe width="560" height="315" src="' + embed_url + '" frameborder="0" allowfullscreen></iframe>';
        jQuery('#video-player').addClass('video-player-opened').html(embed_code);
        e.preventDefault();
   });
});

The reason I add “video-player-opened” class is to apply responsive style to only opened video player so it doesn’t mess up its parent’s style.

Style

The embed code isn’t responsive so we need to make it scale depends on a device’s resolution.

.video-player-opened{
  position:relative;
  padding-bottom:56.25%;
  height:0;
  overflow:hidden;
}
.video-player-opened iframe{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
}

Why padding-bottom:56.25%;? This number is calculated by using the video’s aspect ratio of 16*9 (9 / 16 = 0.5625).

Leave a Comment

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

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close