jQuery To Make a YouTube Video Embed Responsive
HTML
<div id="content" class="youtube-responsive-container">
<iframe class="youtube-responsive" width="560" height="315" src="//www.youtube.com/embed/g9vrNRAqEkU" frameborder="0" allowfullscreen></iframe>
</div><!-- #content -->
CSS
.youtube-responsive-container {
position: relative;
padding-bottom: 55%;
padding-top: 30px; height: 0; overflow: hidden;
}
.youtube-responsive-container iframe,
.youtube-responsive-container object,
.youtube-responsive-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
JavaScript
// Anonymous function for private variables
(function(){
// Function to wrap YouTube iframe in <div class='youtube-responsive-container'> tag to make it responsive
function youtube_embed_responsive() {
$("#content").find(this).wrap("<div class='youtube-responsive-container'></div>");
}
// Assign "this" in funciton below to ".youtube-responsive" YouTube iframe element & iterature over "this" in function using each
$(".youtube-responsive").each(youtube_embed_responsive);
})();