Created
June 8, 2011 13:07
-
-
Save mathiasbynens/1014385 to your computer and use it in GitHub Desktop.
Fluid width YouTube videos of different aspect ratios, by Chris Coyier
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
// Original code from http://css-tricks.com/examples/FluidWidthYouTube/iframe.php | |
$(function() { | |
// find all videos | |
var allVideos = $("iframe[src^='http://www.youtube.com']"), | |
// The thing that is fluid width | |
body = $("body"), | |
// used to cache "this" | |
el; | |
// figure out and save aspect ratio for each video | |
allVideos.each(function() { | |
// cache | |
el = $(this); | |
el | |
// store aspect ratio as data | |
.data('aspectRatio', el.attr('height') / el.attr('width')) | |
// and remove the hard coded width/height | |
.removeAttr('height') | |
.removeAttr('width'); | |
}); | |
// when window is resized | |
// you'll probably want to debounce this | |
$(window).resize(function() { | |
// find new width | |
var newWidth = body.width(); | |
allVideos.each(function() { | |
el = $(this); | |
// resize all videos according to their own aspect ratio | |
el | |
.width(newWidth) | |
.height(newWidth * el.data('aspectRatio')); | |
}); | |
// kick off one resize for good measure | |
}).trigger('resize'); | |
}); |
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
// My rewritten version | |
$(function() { | |
// Find all videos | |
var $allVideos = $("iframe[src^='http://www.youtube.com']"), | |
// The thing that is fluid width | |
$fluidEl = $("body"); | |
// Figure out and save aspect ratio for each video | |
$allVideos.each(function() { | |
$(this) | |
// Store aspect ratio as data | |
.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() { | |
// Find new width | |
var newWidth = $fluidEl.width(); | |
$allVideos.each(function() { | |
var $el = $(this); | |
// Resize all videos according to their own aspect ratio | |
$el | |
.width(newWidth) | |
.height(newWidth * $el.data('aspectRatio')); | |
}); | |
// Kick off one resize for good measure | |
}).resize(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can you make it expand with just the parent container? Instead of to the size of the entire body?