Peter Boomsma
Peter Boomsma

Reputation: 9808

jQuery function if statement

I've created a function called VoteSlide. When I click on on the buttons .prev and .next it does execute the function. But as you can see the function reacts the same to both buttons. So I want the function to react different when a different button is pushed. One function should have margin-left -100% and the other should have margin-left: 100%

But how do I create that small difference? I was thinking about using an if/else statement. But I haven't used to enough to figure out how to apply it in this case (or if it's the right way to solve this).

function VoteSlide() {

  var prev = this;
  $(prev).find(".output").html(function(i, val){return val*1+1});
  $(prev).removeClass("prev")

  $("body").find(".art").each(function(){
    $(this).prepend('<img src="http://no-illusions.nl/random/demo1/assets/images/' + images[index] + '">');
    if(index < images.length+0 ){
      index++;
    }
    else{
      $("#nav" ).fadeOut();
    };
  });

  $(this).closest('body').find(".art img:last").stop().animate
  ({'margin-left': '-100%',}, 500,
   function(){
     $(this).remove();
     $(prev).addClass("prev");
   }
  );
}

$('#nav').delegate('.prev', 'click', VoteSlide);
$('#nav').delegate('.next', 'click', VoteSlide);

Upvotes: 0

Views: 54

Answers (1)

Brian
Brian

Reputation: 7135

You can use an if statement to check the class of the button that was clicked, to determine if it was the prev or next button. Try putting it at the very top of the VoteSlide function:

if($(this).hasClass('prev')) {
  var margin = '-100%';
} else {
  var margin = '100%';
}

Then use the margin variable here:

$(this).closest('body').find(".art img:last").stop().animate(
   {'margin-left': margin},
   500,
   function(){
     $(this).remove();
     $(prev).addClass("prev");
   }
);

Upvotes: 2

Related Questions