three3
three3

Reputation: 2846

Adjust height of iframe when new content is loaded

I have an iFrame that is included in my HTML and is available when the page loads. When the page first loads, the iFrame has no content/src. I am using jQuery to insert content into the iFrame dynamically. When a user clicks a link on my page, the contents of the iFrame are updated. All of this is working for me.

However, I am struggling to adjust the height of the iFrame when new content is loaded. I have tried several solutions on Stack Overflow but with no success. Here is my iFrame code:

<iframe id="myframe" width="100%" frameborder="0"></iframe>

Here is my jQuery that changes the HTML inside of my iFrame:

emailOpened.find('#myframe').contents().find('body').html(email.body);

This works for me. I just need my iFrame to adjust its height based on the height of the content being injected. I have failed on all attempts with this part.

Update

Here is my new HTML:

<iframe id="myframe" width="100%" frameborder="0">
  <body onload="parent.resizeIframe(document.body.scrollHeight);">
</iframe>

Upvotes: 0

Views: 1861

Answers (2)

Spencer May
Spencer May

Reputation: 4506

Call this function directly after the html has been changed.

      function resizeIframe() {
          var newHeight = document.getElementById('myframe').contentDocument.body.scrollHeight;
          document.getElementById('myframe').style.height = parseInt(newHeight,10) + 10 + 'px';
      }

Upvotes: 0

J&#246;rn
J&#246;rn

Reputation: 845

If you need mobile support and allow (user) scrolling for the iframe check out https://github.com/davidjbradshaw/iframe-resizer a as drop-in solution which fixes different issues on iOS and android.

I had to support mobile devices as well and ended up using it after some hours of research and testing. I've also used the provided message channel to send messages to the inner document back and forth.

Upvotes: 1

Related Questions