Reputation: 6352
I have an iframe on my page that I want resized every time the contents changes so that there are no scrollbars. The contents of the frame changes frequently without changing the URL. I want all of the content from the frame to show all the time, without having the screen flicker while the frame is resizing. The parent and frame are on the same domain.
Right now I call a function to set the frame size whenever I think the size has changed. How do I do this without calling this function everywhere?
If it helps, I am using angularJS.
Upvotes: 0
Views: 3990
Reputation: 3767
Try iframe-resizer, a drop-in js module for resizing iframes automatically.
Upvotes: 1
Reputation: 5419
This is a function wich I used on one of my site. I modified the code to be put in a directive.
Note : In the iframe your container must have the ID ifrm_container
<iframe resize-iframe id="iframe" src="...">
.directive('resize-iframe', function() {
return {
restrict: 'A',
link: function ( scope, elm, attrs ) {
var container = elm.contentWindow.document.getElementById('ifrm_container'); // Iframe container. Usualy a div.
function autoResize(){
ifrmNewHeight = container.offsetHeight; // New height of the document.
if(ifrmNewHeight !== ifrmOldHeight) {
ifrmOldHeight = ifrmNewHeight + 30; // +30 for no scrollbar.
ifrm.style.height= (ifrmNewHeight + 30) + "px"; // Set iframe style.
}
setTimeout(autoResize, 250);
}
// First call of autoResize().
autoResize();
};
});
I have tested this solution on all browser even IE7 and it works well but not in a directive (changed some element).
THIS DIRECTIVE IS NOT TESTED
Upvotes: 0
Reputation: 323
Try this, call the re-size function in a event listener, when ever the iframe loads this will be triggered
var iframe = document.getElementById('myIframe');
var resizeFunction= function() {$("#myIframe").css({
height: iframe.$("body").outerHeight()
});};
if(iframe.addEventListener){
iframe.addEventListener('load', resizeFunction, true);
}else if(iframe.attachEvent){
iframe.attachEvent('onload',resizeFunction);
}
Upvotes: 0
Reputation: 1587
You can get the iFrames content height by [iframe].contentWindow.document.body.offsetHeight
. If you don’t know when the the content size changes you have to check it manually by using setInterval()
.
Upvotes: 1