JWDev
JWDev

Reputation: 856

JavaScript: Slider jumps to the wrong ID every 2 steps

I've built a custom, dirt and quick, jQuery/JavaScript slider... which works great, except for one issue.

When using the 'Previous' button, it works perfectly the first time you click it, but then when you click it again, the length of the array becomes '2' when it should be '1' because there are only two results...

Code:

      jQuery("#sliderNext").click(function(event) {
    $("#sliderNext").fadeOut(50);
    $("#sliderPrevious").fadeOut(50);
    setTimeout(function() {
                $("#sliderNext").fadeIn(100);
                $("#sliderPrevious").fadeIn(100);
            }, 900);
      slideNumber++;
      if(slideNumber < image.length && caption.length) {
        jQuery(".slider-image").css("background-image", "url(" + image[slideNumber] + ")");
        jQuery("#caption").text(caption[slideNumber]);
        console.log("if: " + slideNumber);
      }
      else
      {
        slideNumber = 0;
        jQuery(".slider-image").css("background-image", "url(" + image[slideNumber] + ")");
        jQuery("#caption").text(caption[slideNumber]);
        console.log("else: " + slideNumber);
      }

  });

   jQuery("#sliderPrevious").click(function(event) {
    $("#sliderNext").fadeOut(50);
    $("#sliderPrevious").fadeOut(50);
    setTimeout(function() {
                $("#sliderNext").fadeIn(100);
                $("#sliderPrevious").fadeIn(100);
            }, 900);
      slideNumber--;
     console.log(image.length);
      if(slideNumber >= 0 && slideNumber <= image.length) {
        jQuery(".slider-image").css("background-image", "url(" + image[slideNumber] + ")");
        jQuery("#caption").text(caption[slideNumber]);
        console.log("if: " + slideNumber);
      }
      else
      {
        slideNumber = image.length;
        jQuery(".slider-image").css("background-image", "url(" + image[slideNumber] + ")");
        jQuery("#caption").text(caption[slideNumber]);
        console.log("else: " + slideNumber);
        console.log(image.length);
      }

  });

I've tried using different operators, if/else statements, it always sets it to 2 on the second click.

Could anybody point me in the right direction for why it would do this?

Upvotes: 0

Views: 35

Answers (1)

noa-dev
noa-dev

Reputation: 3641

This might be because your click event gets bound the second time to the button and therefore jumps twice.

Try to "unbind" your click events before binding them.

$("#sliderPrevious").unbind();
// and then
jQuery("#sliderPrevious").click(function(event) {...});

Do this to every event that gets bound when intializing the page.

EDIT

var myArray = [a,b];

Note that myArray.length == 2 but myArray[2] is undefined.

Array indexes start at [0] thats why you have to substract 1 from your "counter" variable.

Upvotes: 1

Related Questions