Reputation: 123
In my web project, I have an iframe. It holds one graph, and a table holding values of graph. (graph = google graph api, table=datatables)
Sometimes iframe content height changes by its js applications, not by reloading an html.
So I need to detect those changes originating from js's and increase i-frame size.
How can I detect those changes?
Here is my function that increases i-frame size. (For your reference)
function update_height() {
$('#iframe-1').load( function() {
var $ifbody = $(this).contents().find( 'body' );
$ifbody.css( 'height','auto' );
$(this).height( $ifbody.height() );
});
};
Upvotes: 2
Views: 5582
Reputation: 15103
Since you don't want to use polling, maybe you should consider firing a custom event from the iframe js. Assuming you are also using jquery in the iframe js, you can add this whenever your iframe content changes:
parent.$('#iframe-1').trigger("iframeResize", [$("body").height()]);
Then, in the parent page, set your handler for when the event is fired:
$('#iframe-1').bind('iframeResize', function(event, newSize) {
$(this).height(newSize);
//or whatever else you'd like to do, such as call your update_height() function
});
If you don't want to send the newSize
parameter with the event (or your iframe js does not know it at the time of firing the event), then you can put your update_height()
code into the bind()
handler to get the size of the iframe body.
Upvotes: 2
Reputation: 9567
It seems you're using jQuery:
$('#iframe-1').load(function(){
$(this).height($(this).contents().find('body').height());
});
That should do the trick as long as the iframe domain and protocols match, for the initial load.
Then to keep it updated as the height changes...
$('#iframe-1').contents().find('body').bind('resize', function(){
$('#iframe-1').height($(this).height());
});
Should do it... probably...
Upvotes: 0
Reputation: 5015
the page the iframe is within and the page that is provided as the src of the iframe have to be from the same origin (same origin policy). If that is the case, javascript can talk from one page to the other (postMessage or via HashChange) or by directly accessing the windows parents window and resize the iframe.
access the iframe on the main document from within the iframe;
function updateHeight(newHeight){
parent.document.getElementById("iframe").style.height=newHeight+"px";
}
Upvotes: 0