Categories
Resources Tips Tutorials

Making your videos responsive to screen resolution with JQuery

This is a nice piece of code I found in Stack Overflow, but I love the solution posted by Darwin in October 12 2012 and I tweaked to fit my needs and here is my code:

function adjustVideoRatioToParent(arr){
    var element = (arr.e === undefined)? jQuery('iframe[src*="youtube"]') : jQuery(arr.e); //set element or elements
    var eParent = element.parent(); //capture parent
    var mxWidth = eParent.width(); //get parent width
    var aRatio = (arr.r === undefined || (arr.r && arr.r === 'ws'))? 'ws' : 'std'; //set aspect ratio to be used
    var useRatio;
    //setting ratio
    switch(aRatio){
        case 'std': useRatio = 3/4; break;
        default: useRatio = 9/16;
    }
    element.css({'width':'100%','height':(mxWidth*useRatio)+'px'});
}

The code will look for the parent of the iframe and will calculate the width of this parent and adjust the aspect ratio of the iframe. The parent could be the BODY of the document or any other element as DIV or ARTICLE or SECTION. You choose.

Usage:

Use with any independent object like:
<iframe src="your.youtube.url/id" onload="adjustVideoRatioToParent({e:this,r:'std'});"></iframe>

Or just enter it in you jQuery(document).ready() function if all the videos in the screen will have the same aspect ratio.

jQuery(document).ready(function(){
     adjustVideoRatioToParent({r:'std'}); //for Standard Ratio
     adjustVideoRatioToParent(); //default for Widescreen Ratio
     //also you can use this
     adjustVideoRatioToParent({e:'.standard',r:'std'});
     adjustVideoRatioToParent({e:'.widescreen',r:'ws'});
});

Making YouTube iFrame Responsive

A sample of a code use in a web I’m working on.

How to make it with plain JavaScript? Just watch this video

Hope this helps!
Happy Coding

Leave a Reply