Reputation: 816
I have an iframe pulling in an image and some rows of data (cross domain). The iframe is created with an imbedded javascript file like this:
<script type="text/javascript" src="http://www.domain.com/blah/scriptfile.js?blah_id=001" id="blah_script"></script>
The iframe is being created and its loading the images and data perfectly... so far, so good.
Inside the iframe I want to hide the rows of data and shorten the height of the iframe [-] and when the image is clicked [+] expand the height of the iframe and unhide the rows. I placed the rows in a .
Below is a cut back version of the function being called onclick (and it IS being called). The first line in the function shows how I'm generating the szFrameName and the $folder_id is 001 which is reflected in the szSpanName. When alert() gets called it shows: "blah_iframe_001 blah_cmpnt_001" so the names are correct however the document.getElementById returns null on the blah_iframe but works fine on the blah_cmpnt_
function onclickToggle()
{
var szFrameName = 'blah_iframe_' +"<?php echo $folder_id; ?>";
var szSpanName = "blah_cmpnt_" +"001";
var idFrame = document.getElementById(szFrameName);
var idCmpnt = document.getElementById(szSpanName);
alert(szFrameName +" " +szSpanName);
}
I've tried window.frameElement but that produces an "access denied" error so how do I resize/shorten the iframe?
Upvotes: 1
Views: 9166
Reputation: 13077
Having looked a lots of different solutions to this I ended up writing a simple library to take a account of a number of different use cases. As I needed a solution that supported multiple user generated iFrames on a portal page, supported browser resizes and could cope with the host page JavaScript loading after the iFrame. I also added support for sizing to width and a callback function and allow the override of the body.margin, as you will likely want to have this set to zero.
https://github.com/davidjbradshaw/iframe-resizer
The iFrame code is just a little self-contained JavaScript, so that it's a good guest on other people pages.
The script is then initialised on the host page and has the following available options. More details on what these do on the GitHub page.
iFrameSizer({
log: false,
bodyMargin:null,
sizeHeight:true,
sizeWidth:false,
enablePublicMethods:false,
interval:33,
autoResize: true,
callback:function(messageData){
$('p#callback').html('<b>Frame ID:</b> ' + messageData.iframe.id +
' <b>Height:</b> ' + messageData.height +
' <b>Width:</b> ' + messageData.width +
' <b>Event type:</b> ' + messageData.type);
}
});
If you set enablePublicMethods, it gives you access in the iframe to manually set the iFrame size and even remove the iframe from the host page.
Upvotes: 1
Reputation: 816
In hopes that this will help someone else, I created 3 files on github that shows exactly how to do this... cross domain iframe resizing at its finest.
https://github.com/ppetree/iframe_resize.git
Upvotes: 5