Create Embed Video from Youtube Link and Make It Responsive

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

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

Table of Contents

HTML

We will create a link for the click event and a wrapper to display the 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('[\\?&amp;amp;]v=([^&amp;amp;#]*)').exec(url);
var embed_url = '';
if (video_id &amp;amp;&amp;amp; video_id[1]) {
embed_url = 'http://youtube.com/embed/' + video_id[1];
}
var embed_code = '&amp;lt;iframe width="560" height="315" src="' + embed_url + '" frameborder="0" allowfullscreen&amp;gt;&amp;lt;/iframe&amp;gt;';
jQuery('#video-player').addClass('video-player-opened').html(embed_code);
e.preventDefault();
});
});

The reason I add the “video-player-opened” class is to apply a 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 depending 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 *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. 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