Alec Friedman
Alec Friedman

Reputation: 113

How to get an if statement working with variable inside

This is my code but I cannot get the if statement to stop running based on the condition. It's like the function thinks the variable is always 0 even though i'm adding one every time.

var this_current_position = 0;
var numItems = 8;

if (this_current_position <= 4 ) {
    $(".fa-arrow-right").click(function(){
            $('.mobile-gallery-content').animate({"left": '+=-324'});
            this_current_position += 1;
    });
};

Can anyone find any mistakes in my code?

Upvotes: 0

Views: 35

Answers (1)

phuzi
phuzi

Reputation: 13060

The if statement will only run the first time through the code. At that time this_current_position is always 0 and the click handler will be registered. Each time the click handler is invoked this_current_position will be incremented, but there's no logic in the handler to check this value.

Perhaps you meant to put the check inside the handler:

var this_current_position = 0;
var numItems = 8;

$(".fa-arrow-right").click(function(){
    if (this_current_position <= 4 ) {
        $('.mobile-gallery-content').animate({"left": '+=-324'});
        this_current_position += 1;
    }
});

Upvotes: 3

Related Questions