Created
August 11, 2012 23:28
-
-
Save crazystick/3327796 to your computer and use it in GitHub Desktop.
YouTube iframe Embed and Resize to Content
This file contains 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
<script src="page.js"></script> | |
... | |
<!-- You can set the initial size to something sensible, but it will get resized on loading --> | |
<iframe src="http://www.youtube.com/embed/VIDEO_ID" width="560" height="315"></iframe> | |
... |
This file contains 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
(function($,sr){ | |
// debouncing function from John Hann | |
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ | |
var debounce = function (func, threshold, execAsap) { | |
var timeout; | |
return function debounced () { | |
var obj = this, args = arguments; | |
function delayed () { | |
if (!execAsap) | |
func.apply(obj, args); | |
timeout = null; | |
}; | |
if (timeout) | |
clearTimeout(timeout); | |
else if (execAsap) | |
func.apply(obj, args); | |
timeout = setTimeout(delayed, threshold || 100); | |
}; | |
} | |
// smartresize | |
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; | |
})(jQuery,'smartresize'); | |
// usage: | |
//$(window).smartresize(function(){ | |
// // code that takes it easy... | |
//}); | |
$(function() { | |
// Find all YouTube videos | |
var $allVideos = $("iframe[src^='http://www.youtube.com']"), | |
// The element that is fluid width <-- This needs to be changed! | |
$fluidEl = $("article"); | |
// 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).smartresize(function() { | |
var newWidth = $fluidEl.width(); | |
// Resize all videos according to their own aspect ratio | |
$allVideos.each(function() { | |
var $el = $(this); | |
$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