Spencer Cooley
Spencer Cooley

Reputation: 8851

Javascript if statement is not working correctly

  //this counts how many images exist
  var img_count = $("#gallery_scroller img").length;
  //this is a number where I want the clicks to stop working
  var limit_count = img_count/3;

  var click_count = 1;

  if ( limit_count > click_count){

    $("#down_arrow").click(function(){
      click_count++
      var css_position = -1*click_count*300;
      $('#gallery_scroller img').css('top', css_position);
      alert(css_position+' '+limit_count+' '+click_count);
    });
  };

I put the alert at the end so I can observe the values everytime I click. It just keeps on going even though the click_count is larger than the limit_count. In the if condition, when I replace click_count with an actual number that is larger than the limit_count it works.

Upvotes: 0

Views: 118

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

Your if statement isn't in the code in the click event handler. Once the handler is attached, only the code within the handler will get run when the click occurs.

I'm not entirely sure what your desired result is, but this is probably closer:

//this counts how many images exist
var img_count = $("#gallery_scroller img").length;
//this is a number where I want the clicks to stop working
var limit_count = img_count/3;

var click_count = 1;

$("#down_arrow").click(function(){
    if ( limit_count > click_count){
        click_count++;
        var css_position = -1*click_count*300;
        $('#gallery_scroller img').css('top', css_position);
        alert(css_position+' '+limit_count+' '+click_count);
    }
});

E.g., put the test within the event handler code.


Side note: There's no need for a semicolon at the end of the curly braces on an if block, e.g.:

    if (...) {
    };
//   ^--- no semi here

Side note 2: I've added a semicolon after click_count++. Without it, you're relying on the horror that is automatic semicolon insertion. You were okay because there was a line break after it, but in general, best to learn the rules of where semicolons go and always include them where they're required.

Upvotes: 3

mgraph
mgraph

Reputation: 15338

$("#down_arrow").click(function(){
 if ( limit_count > click_count){
    click_count++
    var css_position = -1*click_count*300;
    $('#gallery_scroller img').css('top', css_position);
    alert(css_position+' '+limit_count+' '+click_count);
  };
});

Upvotes: 0

gonchuki
gonchuki

Reputation: 4134

your condition needs to be inside the event handler:

var click_count = 1;

$("#down_arrow").click(function(){
  if ( click_count < limit_count ){
    click_count++;
    var css_position = -1*click_count*300;
    $('#gallery_scroller img').css('top', css_position);
    alert(css_position+' '+limit_count+' '+click_count);
  };
});

Upvotes: 0

Related Questions