jQuery + If Statement

23,998

Solution 1

You shouldn't use the var keyword again when assigning 1 to animate. By doing this, you are causing a syntax error since animate has already been declared within the same scope.

Solution 2

When you use var to declare a variable, then it becomes a local variable, which means it's new within that scope.

The quick (and dirty) way for you to get the goal you want is something like:

var animate = 0;
$('a').click(function() {
    if (animate === 0) {
        $('#shadow').fadeOut(500);
        animate = 1;  // note the lack of "var"
    }
});

Note that this is probably a pretty imperfect solution; in particular animate doesn't set itself back to 0 (you can do this with a callback function as the second argument to fadeOut, though).

A still better solution is probably to place (and remove) a class on the particular item you're working with:

$('a').click(function() {
    if (!$('#shadow').hasClass('animating')) {
        $('#shadow').addClass('animating').fadeOut(500, function() {
            $(this).removeClass('animating');
        });
    }
});

However, I don't know the details of your implementation, so I'll let you figure out what is right for your particular needs.

Solution 3

You're redefining animate by using var inside the click function.

change

var animate = 1;

to

animate = 1;

This will make it so you set the value of the animate variable in the outer scope and not animate that you are creating in scope within the click function.

HTH

Share:
23,998
Ryan Gillies
Author by

Ryan Gillies

Updated on May 18, 2020

Comments

  • Ryan Gillies
    Ryan Gillies almost 4 years

    I'm trying to teach myself some basic jquery and am having trouble with an if statement I'm trying to use. My code is as follows:

    var animate = 0;
    
    $('a').click(function () {
    if (animate == 0) {
    $('#shadow').fadeOut(500);
    var animate = 1;
    }
    });
    

    I'm hoping to use some else statements further down the line, so that depending on the value of "animate" it will perform a different jquery action when clicked. I'm sure I've overlooked something obvious, but I'm banging my head against a wall trying to figure out what it is.

    Any help would be most appreciated!

  • Ryan Gillies
    Ryan Gillies almost 13 years
    And just like that the problem is solved - lesson learnt, many thanks.