0

I want an animation such that it toggles to slide the div left and right every time I click button. However, when I actually use the code it only slides it to right once and stops working any more.

<script> 
var left = 1;

$(document).ready(function(){
$("button").click(function(){

  if(left==1){
    $("div").animate({left:'250px'});
    left=2;
  }else{ 
    $("div").animate({right:'250px'});
    left=1;
  }

  });
});

</script> 

What's wrong with this code? I couldn't think of a problem.

2 Answers 2

5

Because you're using both left and right, try this:

if( left === 1 ) {
    $("div").animate({left:'250px'});
    left = 2;
}
else { 
    $("div").animate({left:'0px'});
    left = 1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or clear the left: $("div").animate({left:'',right:'250px'});. jsbin.com/OCigILU/1/edit
0

The loop was right, but the css wasn't.

<script> 
var left = 1;

$(document).ready(function(){
$("button").click(function(){
  if(left==1){
    $("div").animate({left:'250px'});
    left=2;
  }
  else { 
    $("div").animate({left:'0px'});
    left=1;
  }
 });
});

</script>         

Comments

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.