Skip to content

Instantly share code, notes, and snippets.

@house9
Created October 21, 2010 15:54
Show Gist options
  • Save house9/638747 to your computer and use it in GitHub Desktop.
Save house9/638747 to your computer and use it in GitHub Desktop.
when the page loads set the height of an iframe based on the height of its contents
/*
Plugin: iframe autoheight jQuery Plugin
Author: original code by NATHAN SMITH; converted to plugin by Jesse House
File: jquery.iframe-auto-height.plugin.js
Description: when the page loads set the height of an iframe based on the height of its contents
Remarks: original code from http://sonspring.com/journal/jquery-iframe-sizing
now made into a plugin and does not match on tag name iframe
TODO: github link
TODO: tests
TODO: examples
TODO: run jslint
*/
(function ($) {
$.fn.iframeAutoHeight = function (options) {
// set default option values
var options = $.extend({
heightOffset: 0
}, options);
// iterate over the matched elements passed to the plugin
$(this).each(function () {
// Check if browser is Safari or Opera. (this seems to cover chrome as well)
if ($.browser.safari || $.browser.opera) {
// Start timer when loaded.
$(this).load(function () {
var iframe = this;
var delayedResize = function () {
resizeHeight(iframe);
};
setTimeout(delayedResize, 0);
});
// Safari and Opera need a kick-start.
var source = $(this).attr('src');
$(this).attr('src', '');
$(this).attr('src', source);
}
else {
// For other browsers.
$(this).load(function () {
resizeHeight(this);
});
}
// since we are in a closure this method cannot be accessed from outside, which is a good thing
function resizeHeight(iframe) {
// Set inline style to equal the body height of the iframed content plus a little
var newHeight = iframe.contentWindow.document.body.offsetHeight + options.heightOffset;
iframe.style.height = newHeight + 'px';
}
}); // end
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment