jQuery iframe load function not woking properly

user3441151 asked
javascript jquery iframe
via

I am using below code

<script type="text/javascript">
    var counter = 0;
    $('iframe').load(function() {
        counter++;
        alert("counter : "+counter);
        alert("iframe len : "+$('iframe').length);
        if (counter == $('iframe').length) {
            doRedirect();
        }
    });

    function doRedirect() {
        alert("Inside doRedirect");
    }
</script>

You can see I put some alert inside the above code. First it gives me the alert counter : 1 and iframe len : 4 after that alert counter : 2 and iframe len : 4 then it will proceed for other action they will not showing the alert counter : 3 and 4 as per the code and it is also not come to doRedirect function.

So please help me what is wrong with this code.


Answer
via

Each time you run $('iframe'), a new query takes place.

You should cache the $('iframe') query, because the way you’re doing it now is susceptible to just the sort of thing you’re reporting. Starting here in your code, I’ll explain…

$('iframe').load( ...

$('iframe') is a collection of <iframe> tags in the DOM when this line runs, and therefore you’re attaching to all iframe tags in that collection, and only to those in that collection.

Later in the function body, you’re comparing a static counter to the number of <iframe> tags in the DOM at a later time, via $('iframe').length. Calling $('iframe') creates a new collection based on the current state of the DOM, which could be different from the original collection.

So this is the most likely source of your trouble. Why? Because between the time you attached the load event handler and the time when this callback fires, anything in the DOM could have changed, including the number of iframe tags; e.g., if you have other scripts doing other things.


Suggested fix.

<script type="text/javascript">
    var $iframes = $('iframe'),
        counter = 0;

    $iframes.load(function() {
        counter++;
        alert("counter : "+counter);
        alert("iframe len : "+$iframes.length);
        if (counter == $iframes.length) {
            doRedirect();
        }
    });

    function doRedirect() {
        alert("Inside doRedirect");
    }
</script>
Share This
Posted in: