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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With