Responsive YouTube Video Embeds

I was recently working on a responsive website where YouTube videos could be embedded in the content. Since the website was responsive the embedded video had to resize based on the width of the content are but since YouTube iframe embeds have a hard coded width and height, the size of the iframe was always fixed regardless of the size of the content area.

One prerequisite I set was that the embed code should simply be copied in without any modifications. I knew that if the embed code was going to require changes that somewhere down the line things would go wrong since someone might forget to make these required changes. So, embed code should be pasted as is.

To make this work I required some Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function resizeIFrame() {
   $('article iframe').each( function() {
 
      // Obtain reference alias to iframe element. 
      var iframe = $(this);
 
      // Get the original iframe width and height.
      var w = iframe.attr('width');
      var h = iframe.attr('height');
 
      // Get the width of the <article> parent element.
      var cw = iframe.parents("article").width();
 
      // Calculate the aspect ratio factor for the new height.
      var s = 1.0 / w * cw;
 
      // Set the new width and height on the iframe.
      iframe.css('width', cw+"px");
      iframe.css('height', (h * s)+"px");
   } );
}
 
$(document).ready( function() {
   resizeIFrame();
 
   $(window).resize( resizeIFrame );
} );

The first important thing to understand about this snippet is that my page content is contained inside an <article> tag as any good front end dev would do these days. It’s also the <article> tag that is defining the width of the content. One thing WordPress does is, it’s wrap the iframe in a <p> tag. In the above Javascript you’ll notice that I use the following jQuery statement to obtain the current content width in pixels:

      // Get the width of the <article> parent element.
      var cw = iframe.parents("article").width();

This little snippet looks for the first <article> tag in one of the parent elements. This means that the iframe can be wrapped in as many tags as you want without breaking the code.

OK. So, the basic gist of the resize code is to use the width and height attributes that are set on the YouTube iframe. We then get the current width in pixels of the content area, calculate the ratio and use this factor to determine the height of the iframe.

In the document.ready we need to manually trigger the first resize and we make sure that when ever the browser is resized we update the size of all the iframes in the content.

This entry was posted in Programming. Bookmark the permalink. Both comments and trackbacks are currently closed.