1

I've a for-loop and it won't pass it's i variable or any kind of a variable into Jquery function coded to run with every loop.

for (var i = 0; i < result.length; i++) {
    $('#frame-' + i + '').fadeOut(function () {
        ALERT(i);
        document.getElementById('frame-' + i + '').getElementsByTagName('img')[0].src = 'img/' + result.cat[i].id + '.png';

    });
    $('#frame-' + i + '').fadeIn();

}

I found that I can use .on or .bind functions but I've no idea how it should be done with fadeOut().

fadeOut.on() won't work.

Any suggestions to get this working?

7
  • 1
    replace frame-'+i+'' with frame-'+i Commented Oct 24, 2013 at 11:06
  • 6
    @DipeshParmar that's not the issue though as i is out of scope in the callback. Commented Oct 24, 2013 at 11:07
  • 1
    Looks like a closure issue Commented Oct 24, 2013 at 11:08
  • 1
    alert() is not the same as ALERT(). Commented Oct 24, 2013 at 11:08
  • 1
    possible duplicate of Javascript closure inside loops - simple practical example Commented Oct 24, 2013 at 11:30

2 Answers 2

3

The problem is by the time your fadeOut completes, the for loop has already completed and as such, the value of i that the fade code is reading, will always be the same (the last value).

Create a closure to pass the value of i. This gives you a local copy of i which won't be overwritten by the for loop. Also change ALERT() to alert() (Javascript is case sensitive).

for (var i = 0; i < result.length; i++) {
    (function(i){
        $('#frame-' + i).fadeOut(function () {
            alert(i);
            document.getElementById('frame-' + i + '').getElementsByTagName('img')[0].src = 'img/' + result.cat[i].id + '.png';

        }).fadeIn();
    })(i);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Closure again!!!

$.each(result, function (i, res) {
    $('#frame-' + i + '').fadeOut(function () {
        alert(i);
        $(this).find('img').get(0).attr('src', 'img/' + res.cat.id + '.png');
    }).fadeIn();
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.