Reputation: 632
I want to make a picture (stickman picture) move from left to right as I click one of the two buttons that say "<<" and ">>". Here's my code,
function personLeft() {
$('#img').animate({left:'50px'});
}
function personRight() {
$('#img').animate({right:'50px'});
}
Here's the buttons,
<button id='left' onclick='personRight()'><<</button>
<button id='right' onclick='personLeft()'>>></button>
For some reason, this doesn't work. It only makes him travel once to the right, or once to the left. I've tried doing this instead:
$(document).ready(function(){
$('#left').click(function(){
$('#img').animate({left:'50px'});
});
$('#right').click(function(){
$('#img').animate({left:'50px'});
});
});
but it just did the same thing as the functions. If you need to see what I mean exactly, here's the link.
So, all I want to know is how can it be made that every time I click the right button, it'll go right for 50 pixels and every time I click the left button, it'll go left for 50 pixels.
Upvotes: 0
Views: 2223
Reputation: 1233
You are currently just settings its position to 50px, what you want to do is add 50px from its current position:
$('#left').click(function(){
$('#img').animate({
left:'+=50px'
});
});
Check http://www.w3schools.com/jquery/jquery_animate.asp - Using Relative Values for more information
Upvotes: 1
Reputation: 189
Instead of specifying directly 50px
you need to add or subtract that from the previous value.
Try doing something like
$('#left').click(function(){
var left = parseInt($('#img').css('left'));
$('#img').animate({left:(left - 50) + 'px'});
});
And something similar for #right
Upvotes: 0
Reputation: 6305
for moving left, try this
$('#img').animate({left:'-50px'});
Upvotes: 0
Reputation:
You can try to move element to the left.
$('#left').click(function(){
$('#img').animate({left:'-50px'});
});
Upvotes: 0