
Nick SchuchOperations Lead
Implementing iframe elements can be troublesome for both content editors and developers, that's even before trying to make them responsive. After some recent project work I'm here to tell you there is an easy way to handle them.
For this project the child page was themed so it was already responsive and fit the entire width of the page so it would work with any iframe size.
The initial setup is straight forward:
We now have the initial ground work complete. Now comes the fun part, making the iframe responsive.
For our recent project we chose the Responsive iframes library. It's simple (the code can be read through in about 5min) and initial implementation is very simple.
<!-- Activate responsiveness in the "child" page -->
<scriptsrc="/js/jquery.responsiveiframe.js"></script>
<script>
var ri = responsiveIframe();
ri.allowResponsiveEmbedding();
</script>
<!-- Corresponding code in the "parent" page -->
<scriptsrc="/js/jquery.js"></script>
<scriptsrc="/js/jquery.responsiveiframe.js"></script>
<script>
;(function($){
$(function(){
$('#myIframeID').responsiveIframe({ xdomain:'*'});
});
})(jQuery);
</script>
Note: The above was taken from the Responsive iframe project page.
Responsive iframe library triggers a resize when the screen size changes. With this in mind we ran into an issue where the child (the page we are displaying in the iframe) would have elements update and add additional height, causing elements to disappear in the borders of the iframe. After reading through the library and some googling I ended up with the following solution. The following is javascript that is added to the child page. It watches for changes in the DOM and sends notifications to the parent.
// When fields are updated (invalid content). $('form').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(event) { ri.messageParent(); })
By default, if the iframe size updates the parent page scrolls to the top, we don't want that. After reading through the code I was able to use the following as a solution on the parents end:
$("#myIframeID").responsiveIframe({ scrollToTop: false });
Note: This is an update to the existing javascript.
We had a requirement to set some css for the child iframe. In this case we only wanted to set the style when the child was in the iframe. Since we cannot set css from the parent, we came up with the following solution.
if (window.self != window.top) { $("html").css('overflow' , 'hidden'); }
Here are some simple elements that ended up making the project work a success. Please let me know approaches you have taken in the comments below.