0

I had this code:

var frames = document.getElementsByTagName("iFrame");
var auto_resize_timer = window.setInterval("autoresize_frames()", 400);
function autoresize_frames() {
    for (var i = 0; i < frames.length; ++i) {
        if (frames[i].contentWindow.document.body) {
            var frames_size = frames[i].contentWindow.document.body.offsetHeight;
            if (document.all && !window.opera) {
                frames_size = frames[i].contentWindow.document.body.scrollHeight;
            }
            frames[i].style.height = frames_size + 'px';
        }
    }
}

That was working fine.

Then, I decided to put it in its own module:

function autoResizeFrames() {
    var frames = document.getElementsByTagName("iFrame");
    window.setInterval("autoresize_frames(frames)", 400);
}

function autoresize_frames(frames) {

    for (var i = 0; i < frames.length; ++i) {
        if (frames[i].contentWindow.document.body) {
            var frames_size = frames[i].contentWindow.document.body.offsetHeight;
            if (document.all && !window.opera) {
                frames_size = frames[i].contentWindow.document.body.scrollHeight;
            }
            frames[i].style.height = frames_size + 'px';
        }
    }
}

And run it in the page like so:

<script type="text/javascript">

    $(document).ready
(
     function () {
         autoResizeFrames();
     }

    );

</script>

But now it does not work? Any ideas why?

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557

3 Answers3

1

When you run:

    window.setInterval("autoresize_frames(frames)", 400);

You are essentially evaling your code in the context of the window. When using setInterval, you should pass a reference to the function instead of a string. You can read why eval is bad at Why is using the JavaScript eval function a bad idea?

Normally you would do:

    window.setInterval(autoresize_frames, 400);

However if your function takes arguments then you will need to wrap it in a function.

The following will work:

window.setInterval(function() {
  autoresize_frames(frames);
}, 400);
Community
  • 1
  • 1
Gazler
  • 83,029
  • 18
  • 279
  • 245
0

In your own function, "frames" is declared internally. You could try removing the "var" keyword so it becomes a global variable.

Kippie
  • 3,760
  • 3
  • 23
  • 38
  • I wouldn't advise polluting the global namespace as the solution. Please see http://stackoverflow.com/questions/39691/javascript-best-practices/39970#39970 – Gazler Feb 21 '13 at 15:32
0

I think the problem might on frames variable which might not be accessible inside setInterval. You can try this

function autoResizeFrames() {
    window.setInterval(function(){
         autoresize_frames(document.getElementsByTagName("iFrame"))
    }, 400);
}
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70