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?
The code you pass as callback to
fadeOutis only executed after ~200ms timeout. But the the code is not blocking. I.e. everything inside the click handler, also statements after the call tofadeOut, is executed immediately.But this should not show the alert twice… anyway, if you want to increment
validateon click, but it should have the the correct value when thefadeOutcallback is called, you can do so with an immediate function: