1

I have an element which I animate to move across the screen. From left:-100px to left:screen-width. I loop this 4 times.

When returning the element back to its original position left:-100px, I don’t want it to be seen moving across the screen (from right to left) really fast.

I tried to do it by hiding the element with .hide() and then showing it after a while (so that it has time to move back to its initial position). But this doesn’t work:

$('.snake-image').hide();
$('.snake-image').css('top', height / 2).css('left', currentPos);
setTimeout(function(){$('.snake-image').show();},1000);

Code:

$('body').append('<a href="#"><img src="https://dl.dropboxusercontent.com/u/48552248/projects/covve/website/2015/public/images/snake.png" class="snake-image" style="position:absolute;top:0;" />');

function goRight(currentPos) {
  $('.snake-image').animate({
    left: currentPos
  }, 100);
}

function moveSnake() {
  while (currentPos <= width) {
    goRight(currentPos);
    currentPos += 20;
    console.log(width + " x " + currentPos);
  }
}

var currentPos,
    height = $(window).height(),
    width = $(window).width(),
    i = 4;

var intervalID = setInterval(function(){
  if (i > 0){
    currentPos = -100;
    $('.snake-image').hide();
    $('.snake-image').css('top', height / 2).css('left', currentPos);
    setTimeout(function(){$('.snake-image').show();},1000);
    moveSnake();
    i--;
    console.log('Interval 1');
  } else {
    clearInterval(intervalID);
  }
}, 100);

Demo: http://jsfiddle.net/m0epjLym/

2 Answers 2

1

you could use the animate callback triggered at the end of the animation, you can move your item back in the origina position and then call again the animation

Fiddle:http://jsfiddle.net/xgknu376/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this. I’m trying to add the setInterval() (timeOut() could also work) inside the animate callback somehow, so that it waits a bit before triggering animation again. But I can’t get it to work. It eats up two loops (4 and executes only 2).
i added a line to do that, same fiddle, you should use setTimeout instead of setInterval, in this case
1

You can do this:

$('.snake-image').animate({'opacity': 0}, 0);
$('.snake-image').animate({'top': height / 2}, 0).animate({'left': currentPos}, 0).delay(1000).animate({'opacity': 1}, 0);

The delay function will only work on items that are in the animation queue.

Fiddle: http://jsfiddle.net/y995cts3/3/

1 Comment

Thanks, it works. However, a refactor should be done, as the code is messy :) Exploring ways to “improve” it.

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.