0

I have an iframe that I populate the src of at runtime:

$(iframe).attr("src", "<my html page uri>");

Followed by:

    $(iframe).load(function() {
      //Copy style from parent
      if (setStyles) {
        setStyles = false;
        var linkTags = window.parent.document.head.getElementsByTagName("link");
        for (var i = 0; i < linkTags.length; i++) {
          if (linkTags[i].rel === "stylesheet") {
            var node = linkTags[i].cloneNode();
            node.href = linkTags[i].href;
            this.contentDocument.head.appendChild(node);
          }
        }
      }

      //add some elements dynamically

      var windowHeight = iframe.contentWindow.document.body.scrollHeight;
      $(iframe).height(windowHeight + 'px');
    });

The second last 2 lines of code are there to resize the frame to fit its content after I appended some elements.

This works, but the problem is the CSS that I dynamically added resizes some of the elements, and that means the frame is the wrong height again.

Do I need to chain the dynamic CSS addition and the resizing of the frame so that the CSS is applied to the elements before the re-size happens?

If so, how? Thanks

1
  • 1
    I think using a setTimeout with 100-200 milliseconds to resize the frame could help. I'm not exactly sure though.. Commented Aug 8, 2016 at 7:20

1 Answer 1

1

You have to wait until the CSS file is loaded before reading the scrollHeight property. To achive it, you can add an onload event handler to the link node before calling appendChild.

$(node).load(function() {
    var windowHeight = iframe.contentWindow.document.body.scrollHeight;
    $(iframe).height(windowHeight + 'px');
} ) ;
// Before this:
this.contentDocument.head.appendChild(node);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.