Adjust width and height of iframe to fit with content in it
I need a solution for auto-adjusting the
height of an
iframe to barely fit its content. The point is that the width and height can be changed after the
iframe has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.
All solutions given thus far only account for a once off resize. You mention you want to be able to resize the iFrame after the contents are modified. In order to do this, you need to execute a function inside the iFrame (once the contents are changed, you need to fire an event to say that the contents have changed).
I was stuck with this for a while, as code inside the iFrame seemed limited to the DOM inside the iFrame (and couldn’t edit the iFrame), and code executed outside the iFrame was stuck with the DOM outside the iFrame (and couldn’t pick up an event coming from inside the iFrame).
The solution came from discovering (via assistance from a colleague) that jQuery can be told what DOM to use. In this case, the DOM of the parent window.
As such, code such as this does what you need (when run inside the iFrame) :
one-liner solution for embeds:
starts with a min-size and increases to content size. no need for script tags.