Last active
April 14, 2020 19:10
-
-
Save bradoyler/a02a2f3ec3fbeb2b32ccabb80b782304 to your computer and use it in GitHub Desktop.
adaptive iframe using postMessage()
This file contains hidden or 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
<h2> Hello World! </h2> | |
<script> | |
function iframeResize() { | |
var body = document.body, html = document.documentElement; | |
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); | |
var location = document.location.href; | |
window.parent.postMessage(["setHeight", height, location], "*"); | |
} | |
iframeResize(); | |
$(window).resize(iframeResize); | |
</script> |
This file contains hidden or 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
<iframe id="iframe1" src="child.html" frameborder="0" width="100%" scrolling="no" height="0"></iframe> | |
<script> | |
window.addEventListener('message', function(e) { | |
var $iframe = document.getElementById('iframe1'); | |
var height = e.data[1]; | |
if (e.data[0]==='setHeight') { | |
$iframe.style.height = height + 'px'; | |
} | |
}, false); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment