Reputation: 597
Been learning Jquery and been trying to write a little bit of code that does an animation when you click a button and does the opposite when you click it again (basically moving a circle from right to left each time you click the button. Quite a simple animation, just struggling to get it to do it using an if/else statement in Jquery)
Currently I am at:
$(document).on('click', '#sub', function(){
var moved = 0;
if (moved == 0) {
$('.circle').animate({'margin-left': "300px"});
moved = 1;
}
else{
moved = 0;
$('.circle').animate({'margin-left': "-300px"});
}
});
So I am trying to move .circle right 300px, it runs the if statement part fine, its when I change moved to a a value of 1 that nothing happens. Should I maybe using a while loop or what should I maybe be doing differently?
Upvotes: 3
Views: 2185
Reputation: 352
Depending on the browsers you need to support, it's probably better to hand of the animation to the css. Simple toggle a class when clicking on the circle and use a css transition.
Something like this: JS
$('.circle').on('click', function() {
$(this).toggleClass('clicked');
}
CSS
.circle { transition: margin-left 0.2s; margin-left: -300px; }
.circle.clicked { margin-left: 3OOpx; }
Upvotes: 3
Reputation: 5499
You should declare your moved
var more globally. Now when the click event is triggered moved
will always be 0
because it set this way.
(function() {
var moved = 0;
$(document).on('click', '#sub', function(){
if (moved == 0) {
$('.circle').animate({'margin-left': "300px"});
moved = 1;
}
else{
moved = 0;
$('.circle').animate({'margin-left': "-300px"});
}
});
})();
Now it will "save" the state of moved
variable outside the click event scope.
Edit, a little extra a shorter version of the code:
(function() {
var moved = 0;
$(document).on('click', '#sub', function(){
$('.circle').animate({
'margin-left': (moved ? "-300" : 300 ) + "px"
}, 500, 'swing', function() {
moved = !moved;
// or
moved = (moved ? 0 : 1);
});
});
})();
Upvotes: 1
Reputation: 1104
You are setting moved = 0 each time just before your if statement...
$(document).on('click', '#sub', function(){
var moved = 0; // <- This line here!
if (moved == 0) {
$('.circle').animate({'margin-left': "300px"});
moved = 1;
}
else{
moved = 0;
$('.circle').animate({'margin-left': "-300px"});
}
});
You'll need to move the declaration outside the function so it doesn't reset it each time.
Upvotes: 1
Reputation: 2996
Try something like this. Add class to the element when you first click and remove it on second click.
$(document).on('click', '#sub', function(){
if($('.circle').hasClass("clicked")){
$('.circle').animate({'margin-left': "300px"});
$('.circle').removeClass("clicked");
}else{
$('.circle').animate({'margin-left': "-300px"});
$('.circle').addClass("clicked");
}
});
Upvotes: 0