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?

Answers


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>

Need Your Help

How to get correct day number in my country?

php date

I'm using date('j') function in calendar. The problem is that it returns not correct day. For example in my country today is day 17 and this function return day 16. How to fix this?

Z-index of Marker higher than that of Infobox

javascript jquery css google-maps google-maps-api-3

I am using Google Maps API V3 to create a marker and the Infobox library to create custom infowindows.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.