Luca Donati Luca Donati - 3 months ago 9
jQuery Question

can't change var inside conditional

I have a button with a debounce :

js:

var startClick = true
var finishClick = false

$(document).ready(function(){
if(startClick == true) {
$("#enter").click(function(){
finishClick = true;
startClick = false;
$("#start").animate({bottom: "+=1000px"}, "slow");
$("#finish").animate({bottom: "+=1000px"}, "slow");
});
};

if(finishClick == true) {
$("#back").click(function(){
finishClick = false;
startClick = true;
$("#back").animate({top: "+=5px"}, "200");
$("#start").delay("400").animate({bottom: "-=1000px"}, "slow");
$("#finish").delay("400").animate({bottom: "-=1000px"}, "slow");
$("#back").delay("400").animate({top: "-=5px"}, "0");
});
};
});


I click on the start button and the page slides up like expected, but when I click on the finish button nothing happens, as if finishClick isn't set to true, because when I set finishClick to true at the start of the script both buttons will work normally, back and forth.

Answer

You should move the if condition inside click handler

var startClick = true
var finishClick = false

$(document).ready(function() {

    $("#enter").click(function() {
        if (startClick == true) {
            finishClick = true;
            startClick = false;
            $("#start").animate({ bottom: "+=1000px" }, "slow");
            $("#finish").animate({ bottom: "+=1000px"}, "slow");
        };
    });

    $("#back").click(function() {
        if (finishClick == true) {
            finishClick = false;
            startClick = true;
            $("#back").animate({top: "+=5px" }, "200");
            $("#start").delay("400").animate({ bottom: "-=1000px"}, "slow");
            $("#finish").delay("400").animate({bottom: "-=1000px"}, "slow");
            $("#back").delay("400").animate({top: "-=5px"}, "0");
        };
    });

});