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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!