jmasterx
jmasterx

Reputation: 54113

Why is this function not working?

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

Upvotes: -1

Views: 174

Answers (3)

Muthu Kumaran
Muthu Kumaran

Reputation: 17910

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);
}

Upvotes: 0

Gazler
Gazler

Reputation: 84150

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);

Upvotes: 1

Kippie
Kippie

Reputation: 3820

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

Upvotes: 0

Related Questions