AeroCross
AeroCross

Reputation: 4319

jQuery callbacks messing with variable scopes and functions?

Good morning people - I've been having this problem for hours and I can't isolate it.

I have this piece of jQueryzed JavaScript:

jQuery(document).ready(function() {
    var validated = 1;

    jQuery('#help_continue').click(function() {
        jQuery('#step' + validated + ', #step' + validated + '_help').fadeOut(200, function() {
            jQuery('#step' + validated + '_help').removeClass('visible').find('.visible').removeClass('visible');
            jQuery('#step' + (validated + 1) + '_help').addClass('visible');
            jQuery('#step' + (validated + 1) + '_help div:first').addClass('visible').css({display: 'block'});
            jQuery('#step' + (validated + 1) + ', #step' + (validated + 1) + '_help').fadeIn(200);
        });
    });
});

All good, nothing too fancy. If bound to HTML, it works as expected.

The thing is that, when I add this to the mix:

jQuery(document).ready(function() {
    var validated = 1;

    jQuery('#help_continue').click(function() { 
        jQuery('#step' + validated + ', #step' + validated + '_help').fadeOut(200, function() {
            jQuery('#step' + validated + '_help').removeClass('visible').find('.visible').removeClass('visible');
            jQuery('#step' + (validated + 1) + '_help').addClass('visible');
            jQuery('#step' + (validated + 1) + '_help div:first').addClass('visible').css({display: 'block'});
            jQuery('#step' + (validated + 1) + ', #step' + (validated + 1) + '_help').fadeIn(200); alert(validated); // this...
        });
        validated++; // ...and this.
    });
});

The alert it shown TWICE, and the "validated" variable is NEVER = 1 inside the function - always 2.

I'm no JavaScript guru for sure, but I definitely know that that's just plain wrong, unless I'm missing something. I come from a PHP background, and I know that JavaScript has its idiosyncrasies, but this is just weird.

I'm using jQuery 1.5 if it matters. Anyone knows what's happening?

Upvotes: 0

Views: 256

Answers (1)

Felix Kling
Felix Kling

Reputation: 816272

The code you pass as callback to fadeOut is only executed after ~200ms timeout. But the the code is not blocking. I.e. everything inside the click handler, also statements after the call to fadeOut, is executed immediately.

jQuery('#help_continue').click(function() {
    // first 
    jQuery('....').fadeOut(200, function() {
        // second
    });
    validated++; // first
});

But this should not show the alert twice... anyway, if you want to increment validate on click, but it should have the the correct value when the fadeOut callback is called, you can do so with an immediate function:

jQuery('#help_continue').click(function() {       
    (function(validated) {
        jQuery('....').fadeOut(200, function() {
            // ...
        });
    }(validated));
    validated++;
});

Upvotes: 1

Related Questions