Skip to content

Instantly share code, notes, and snippets.

@akaihola
Created August 28, 2012 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaihola/3497187 to your computer and use it in GitHub Desktop.
Save akaihola/3497187 to your computer and use it in GitHub Desktop.
HTML iframe which resizes according to its contents
// Add this JS to the parent window, replacing the URL and width
// appropriately.
if (document.location.search == '?debug=1') {
document.write('<div id="autosizing-iframe-debug" style="position:absolute;width:233px;height:10em;overflow:scroll;margin-left:-233px;background:#cff;"></div>');
};
document.write('<iframe src="http://OTHERDOMAIN.COM/IFRAME/URL/" width="547px" height="10000px" frameborder="0" scrolling="no" id="autosizing-iframe" style="border: none;"></iframe>');
(function() {
var debug = document.getElementById("autosizing-iframe-debug"),
resizeIframe = function(event) {
var elem = document.getElementById("autosizing-iframe"),
y = elem.offsetTop;
if (debug) {
debug.innerHTML +=
'<br>' +
event.data.autosizingIframeExtra +
'/' +
event.data.autosizingIframeHeight;
debug.scrollTop = 10000;
}
elem.style.height = event.data.autosizingIframeHeight;
while (elem = elem.offsetParent) {
y += elem.offsetTop;
}
window.scrollTo(0, y);
};
if (window.addEventListener) window.addEventListener("message", resizeIframe, false);
else window.attachEvent("message", resizeIframe);
})();
// Add this JS to the iframe, implementing the getHeight() logic and
// adding extra message data for debugging if needed.
$(window).on('pagechange', function(event, data) {
var getHeight = function() {
// Detect page content height.
// As an example, the top position of a dummy footer is used here.
return Math.floor($('#footer', data.toPage).position().top);
},
postHeight = function(height) {
parent.postMessage(
{autosizingIframeHeight: height + 'px',
autosizingIframeExtra: 'any extra data to pass to the parent window'},
'*'
);
},
firstHeight = getHeight();
postHeight(firstHeight);
setTimeout(function() {
var newHeight = getHeight();
if (newHeight > firstHeight) postHeight(newHeight);
}, 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment