Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment variable using jquery

I feel like this is a pretty basic thing, but I cant seem to find the solution. Im trying to increment a value after the loading of an IFRAME.

the code looks like this:

var x=0;
$(document).ready(function() {
        $('#iframe-2').load(function() {
            var x=x+1;        
        });
        $('#iframe-3').load(function() {
            var x=x+1;    
        });
        $('#iframe-4').load(function() {
            var x=x+1;        
        });
        $('#iframe-5').load(function() {
            var x=x+1;        
        });
    });

What I want to do is give a number of loaded iframes that updates when an iframe completes its loading. The output code is like this currently:

<script language="javascript">
document.write(x + " Results");
</script>

thanks a ton in advance for any help!

like image 525
user791187 Avatar asked Jul 05 '12 05:07

user791187


2 Answers

You declare local variable in the load callback function, so it will not increase the global x, you could declare var x inside of dom ready callback function, and use it in load callback function.

$(document).ready(function() {
    var x = 0;
    $('#iframe-2').load(function() {
        x++;        
    });
    $('#iframe-3').load(function() {
        x++;
    });
    $('#iframe-4').load(function() {
        x++;  
    });
    $('#iframe-5').load(function() {
        x++;  
    });
});

Edit: After this, document.write(x + " Results"); still won't work, because it executes before the iframe has been loaded. You need to do a check asynchronously.

Here is the live demo.

$(document).ready(function() {
    var x = 0;
    $('iframe').load(function() {
        x++;        
    });
    var time_id = setInterval(function() {
      $('#count').text(x);
      if (x === $('iframe').length) {
        clearInterval(time_id);
      }
    }, 200);
});​

The html:

<iframe  src="http://www.w3schools.com"></iframe>
<iframe  src="http://www.w3schools.com"></iframe>
<iframe  src="http://www.w3schools.com"></iframe>
<iframe  src="http://www.w3schools.com"></iframe>
<hr>
Loaded iframe count: <span id="count">0<span>
like image 95
xdazz Avatar answered Nov 04 '22 10:11

xdazz


You should change

var x = x+1;

to

x = x+1

Because the var keyword is creating a new variable every time in your every load so global variable x is not getting updated/incremented.

like image 42
The Alpha Avatar answered Nov 04 '22 09:11

The Alpha