Created
August 28, 2012 10:55
-
-
Save akaihola/3497187 to your computer and use it in GitHub Desktop.
HTML iframe which resizes according to its contents
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
// 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); | |
})(); |
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
// 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