November 26, 2010
jQuery question regarding if statement and position moving
Question by alexcu
I’m trying to write a program where basically the user clicks on an image and the image will then move to the right by 25px. The image moves when I click on it, but I tried to add a piece of code which makes the image return to the left of the window when it passes the right side of the window. I’ve tried using an If statement in the animation’s procedure but it doesn’t seem to work. Here’s what I have:
$('#image').click(function() {
$(this).animate({
left: '+=155',
function() {
if ($(this).left > $(document).width) {
$(this).left = 0
}
};
});
});
Am I using the wrong syntax or is my function wrong? Thanks for your help.
Answer by Starx
Where is your duration?
Try this,
$('#image').click(function() {
$(this).animate(
{
left: '+=155'
},
5000,
function() {
if ($(this).left > $(document).width) {
$(this).left = 0
}
);
});