0

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);

1 Answer 1

2

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");
   }
);
Sign up to request clarification or add additional context in comments.

2 Comments

You made a small typo in your first post, but it gave me the right answer! A question though, what happens if you have more then 5 buttons to choose from? Do you have to write a lot of if/else statements? Or is there an better way?
Not sure I completely follow. Should each button click change the outcome of the VoteSlide method differently? You should be able to iterate on the code a bit and make it work more efficiently as you code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.