Created
February 19, 2015 12:50
-
-
Save sohelamin/d1311cb4d692c75b6bc6 to your computer and use it in GitHub Desktop.
YouTube video fluid width height with jquery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just change your youtube video container class.
eg: $fluidEl = "div.youtube-wrapper";