Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save house9/853055 to your computer and use it in GitHub Desktop.
Save house9/853055 to your computer and use it in GitHub Desktop.
/*
see README: http://github.com/house9/jquery-iframe-auto-height
*/
(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 Opera or Safari(Webkit so 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);
});
}
// resizeHeight
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';
}
// public resize method
$.fn.resizeHeight = function () {
resizeHeight($(this).get(0));
}
}); // end
}
})(jQuery);
// usage
<iframe id="my-iframe" />
// get a jquery reference to an iframe
var myIframe = jQuery('#my-iframe');
// apply the initial resizing for page load
myIframe.iframeAutoHeight();
// later code can re-fire on this to resize when not a reload
myIframe.resizeHeight();
// I think this would work calling back from the iframe
parent.myIframe.resizeHeight();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment