Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasbynens/1014385 to your computer and use it in GitHub Desktop.
Save mathiasbynens/1014385 to your computer and use it in GitHub Desktop.
Fluid width YouTube videos of different aspect ratios, by Chris Coyier
// 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');
});
// 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();
});
@casale
Copy link

casale commented Apr 16, 2013

How can you make it expand with just the parent container? Instead of to the size of the entire body?

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