Skip to content

Instantly share code, notes, and snippets.

@sohelamin
Created February 19, 2015 12:50
Show Gist options
  • Save sohelamin/d1311cb4d692c75b6bc6 to your computer and use it in GitHub Desktop.
Save sohelamin/d1311cb4d692c75b6bc6 to your computer and use it in GitHub Desktop.
YouTube video fluid width height with jquery
// By Sohel Amin www.sohelamin.com or www.appzcoder.com
$(function() {
// Find all YouTube videos
var $allVideos = $("iframe[src^='http://www.youtube.com']"),
// The element that is fluid width
$fluidEl = "div.youtube-wrapper";
// Figure out and save aspect ratio for each video
$allVideos.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
// (You'll probably want to debounce this)
$(window).resize(function() {
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
var newWidth = $el.parent($fluidEl).width();
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all videos on page load
}).resize();
});
@sohelamin
Copy link
Author

Just change your youtube video container class.
eg: $fluidEl = "div.youtube-wrapper";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment