2

I've been trying to adjust the size of an iFrame based on its content by using info from here. His demo is located here.

I am using the following:

$("#IframeId").load(function() {
    $(this).height( $(this).contents().find("body").height() );
});

Is the .find("body") checking for "body" in the header section of the inner iframe content? I do see that in the hosted page.

I also added the following to the above code:

 alert($(this).height( $(this).contents().find("body").height()));

I don't see the alert.

Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • you are using the approach of the linked question's question, not answer, the opener of that question clearly mentioned his approach does not work. why don't you copy one of the solutions suggested in the answers in there? – Davide Piras Mar 18 '13 at 22:50
  • Check out the answers to this question: http://stackoverflow.com/questions/701339/resizing-iframe-to-fit-its-content/4585053 – Ferruccio Mar 18 '13 at 23:26
  • Have the page in the frame work out its height and then use postMessage to tell the parent. – Mark Holland Mar 18 '13 at 23:30

1 Answers1

1

I think you have to try to find the height of a specific element in the source of the IFrame, instead of the html tag itself, since it doesn't have a specified height. Here is a working example:

$("#IframeId").load(function() {
    $(this).height( $(this).contents().find("#box").height() ); //box can be changed to the id of the element you want
});

If you have a container div that has the width you want the Iframe to be, you can use its id, instead of box. (Note: box was the id of the main element in this JsFiddle example.)

Jsterman
  • 333
  • 1
  • 7
  • Thanks. I don't see my alert triggering inside the iframe load. It's grabbing an HTML element with the runat=server attribute, which turns into some mangled ID at runtime. But $("#IframeId") should work for that right? – 4thSpace Mar 19 '13 at 01:56
  • I think my jQuery for getting the server control reference is incorrect. I put this in the alert: $("#IframeId").attr('id'). It gave an undefined. When I replace #IframeId with the mangled asp.net generated ID, I see the ID in the alert. – 4thSpace Mar 19 '13 at 02:34
  • What `$("#iframeid").attr('id')` is doing is it is asking for the element that has the id "iframeid". Since you most likely don't have an element with id "iframeid", this code is returning undefined. if your using Asp.NET 4.0, you can add `ClientIDMode="Static"` to you attributes on your iframe. – Jsterman Mar 19 '13 at 02:54