catandmouse
catandmouse

Reputation: 11809

jQuery animation loop not working even if function is called

I have this code:

HTML:

<div class="rotatingbg"> 
      <div id="bg1"></div>
</div>

jQuery:

function animatebg() {
   $('#bg1').animate({left:'-4500px'}, 25000, 'linear', animatebg);
}

However, the animation only runs one time and doesn't loop infinitely even if I called the function within the function.

What's missing or incorrect?

Upvotes: 3

Views: 59

Answers (2)

guest271314
guest271314

Reputation: 1

Try setting #bg1 left to 4500 + window.innerWidth + $(this).width() + "px" within complete callback, which should render element to right of viewport before calling animatebg recursively

function animatebg() {
  $("#bg1").animate({
    left: "-4500px"
  }, 25000, "linear", function() {
    $(this).css("left", 4500 + window.innerWidth + $(this).width() + "px");
    animatebg();
  });
}

animatebg();
#bg1 {
  position: relative;
  left: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="rotatingbg">
  <div id="bg1">abc</div>
</div>

Upvotes: 0

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

You need to have a counter-animation that resets the element back to its original location, otherwise once your element reaches -4500px, it will animate the element moving to the exact same spot, which will not produce any visual change.

Here is an example that has two animations - one that animates forwards, and one that animates back:

function animatebg() {
   $('#bg1').animate({left:'100px'}, 2500, 'linear', animateback);
}

function animateback() {
   $('#bg1').animate({left:'0px'}, 2500, 'linear', animatebg);
}

animatebg();
#bg1 {
    background-color: black;
    width: 100px;
    height: 100px;
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rotatingbg"> 
      <div id="bg1"></div>
</div>

JSFiddle Version: https://jsfiddle.net/cqd3n5wL/

Upvotes: 4

Related Questions