Search code examples
javascriptvariablesscopeimagesloaded

How to use variables in imagesLoaded callback function?


I'm trying to do something very simple, but I'm obviously doing something wrong. Here is the code:

var targets = Array(
    $('.someDiv'),
    $('.myDiv')
    );
// This "for" loop check if the Class exists and if so it runs a code
for (var i = targets.length - 1; i >= 0; i--) {
    // make the target a jQuery object
    var $target = targets[i];
    // if the target exists
    if ( $target.length > 0 ) 
    {
        console.log($target);
        // run some code after every image is loaded
        $target.imagesLoaded( function()
        {
            console.log($target);
            $target.addClass('blue');
        });
    }
}

which somehow doesn't work. The JsFiddle example is here

Is it just impossible to pass a variable without hacking imagesLoaded plugin? Or am I missing something?


Solution

  • If you want the variable to retain the value it had when calling imagesLoaded(), you can use an IIFE:

    var myVar = 'someContent';
    
    (function(myVar) {
        $('.myDiv').imagesLoaded( function() {
            console.log(myVar);
        });
    })(myVar);
    

    Take this example:

    var myVar = 'some content';
    
    (function(myVar) {
        setTimeout(function() {
            console.log(myVar);
        }, 1000);
    })(myVar);
    
    myVar = 'some other content';
    console.log(myVar);
    

    It will log some other content and then, a bit later some content, as was the initial value.