iFrame auto-resize with jQuery
Inline frames are not the prettiest of HTML elements, but they can make your life a hell of a lot easier, especially with branching web application control panels, full of modals and cross-referenced entities. It’s easy to design/develop such interface if you know the height of the iFrame
element, which is almost never the case. So here’s the handy solution based on jQuery and with a little help of server-side scripting. Obviously, you’d need to include jQuery in both files.
Parent page
<iframe id="iframe-123" src="iframe.php?iframe_id=iframe-123" scrolling="no" frameborder="0"> </iframe> <script type="text/javascript"> function updateIframeSize(x,y){ if (x != '') { $('#' + x).height(y + 'px'); } } </script>
Inline frame page
<?php $iframe_id = isset($_GET['iframe_id']) ? $_GET['iframe_id'] : ''; ?> <body>...</body> <script type="text/javascript"> function updateParent() { parent.updateIframeSize('<?= $iframe_id ?>',$('html').height()); } $(document) .ready(updateParent) .click(updateParent); </script>
For faster performance use the old school “dirty” method:
<?php $iframe_id = isset($_GET['iframe_id']) ? $_GET['iframe_id'] : ''; ?> <body onload="updateParent()" onclick="updateParent()"> ... </body> <script type="text/javascript"> function updateParent() { parent.updateIframeSize('<?= $iframe_id ?>',$('html').height()); } </script>
You might want to give the iFrame
reasonably small initial height in CSS, so the parent page doesn’t excessively flick and jump back and forth while the iFrame
content is loading.
To make it completely client-side, read the value from iframe_id
with window.location.search property.