3

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?

0

2 Answers 2

4

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/

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

Comments

0

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>

Comments

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.