-3

I have an Iframe containing a div tag with "firstHeadSection" id.

after iframe is loaded, I append this code to iframe:

    <script>
    $(window).on("resize", function(){
    alert($("#firstHeadSection").height())
    })
    </script>

The Js code will be inserted but after I resize window, it alerts null.

JQuery is included in the iframe.

What should I do?

Shadow78
  • 1
  • 1
  • 3
    Possible duplicate of [Insert content into iFrame](http://stackoverflow.com/questions/21795761/insert-content-into-iframe) – David Gourde Jul 04 '16 at 15:47
  • 2
    We would probably need to see some more JS/HTML with regards to how you insert the iframe, how you append the script etc... – somethinghere Jul 04 '16 at 15:54
  • Most likely there's no element with id `firstHeadSection` at the time you're trying to refer it. Make sure you don't have typos in the `id`s, and validate the markup in the iframe.. – Teemu Jul 04 '16 at 16:09

2 Answers2

0

You have to access to the main page, so you have to prepend "parent". Try something like this: (not tested)

parent.$.fn.resize(function() {
    alert($("#firstHeadSection").height());
});
0

Your code looks for the object with id "#firstHeadSection" in $(window), but with iframe you have to query its DOM like:

<script>
  $(window).on("resize", function(){
    alert($("#iFrameID").contents().find("#firstHeadSection").height())
  });
</script>

I haven't test it... Please post more of your code to be able to do it reliably...

DIEGO CARRASCAL
  • 1,999
  • 14
  • 16
  • 1
    If the code is _inside_ the iframe, then this wouldn't work. CORS also applies in some cases. I think we need more code to be able to help here. – somethinghere Jul 04 '16 at 16:02
  • Yes you are right, but I think his problem is in the scope where he is looking for the DOM object, I believe jQuery is looking for it outside the iframe... he should refer to the iframe internal DOM as an object and query it, well at least give it a try... – DIEGO CARRASCAL Jul 04 '16 at 18:57
  • Might be, but he also mentions 'after iframe is loaded, I append this code to iframe', which doesn't rule this out, but we need more information... – somethinghere Jul 04 '16 at 18:58
  • yes, is he appending the code to the iframe DOM or to the iframe element... – DIEGO CARRASCAL Jul 04 '16 at 19:00
  • 1
    In that case the code would, when done correctly, run _inside_ the iframe, right (again, disregarding possible CORS errors)? I'm unsure and I don't want to fix on an idea until the OP gives us a little more to go on than guesses. – somethinghere Jul 04 '16 at 19:01