Target YouTube iFrames for Responsiveness

[email protected]

by Ryan Brackett

HTML

<h1>Target YouTube iFrames for Responsiveness</h1>
This is an example of how to make only YouTube iframes responsive while leaving other iframes untouched. Drag the center bar to see the responsiveness of the YouTube iframe below. This is done using jQuery. The script wraps a div around iFrames with a specific string in the url. This div uses CSS to make the videos scale fluidly per ratio ratio.
<br/>
<br/>
<div class="wrapper">
    <iframe src="http://www.youtube.com/embed/orGLMOta2m0" frameborder="0" allowfullscreen></iframe>
</div>

CSS

body {
    font-family: arial;
    font-size: 12px;
    line-height: 18px;
}
.wrapper {
    width: 70%;
    margin: auto;
}
h2 {
    font-size: 15px;
}
iframe {
    width: 100%;
}
.responsive-vid {
    width: 100%;
    font-size: 12px;
    height: 0px;
    padding-top: 56.2%;
    position: relative;
}
.responsive-vid iframe {
    width: 100%!important;
    height: 100%!important;
    position: absolute;
    top: 0px;
}

JavaScript

$(document).ready(function () {

    // Target YouTube iFrames for Responsive Videos
    $('iframe[src*="youtube.com"]').each(function () {
        $(this).wrap("<div class='responsive-vid'></div>");
        var ytextras = "?showinfo=0&iv_load_policy=3&controls=0";
        $(this).attr('src', function (i, currentAttribute) {
            return currentAttribute + ytextras;
        });
    });

});