Recursive animation in jQuery not working

I created a function to scroll multiple images horizontally in the header of my website. Therefore, inside my header, I have code similar to this:

<div class='images'> <!-- this div is 150% wide with overflow hidden --> <img src=... /><img src=... /><img src=... /><img src=... /> </div> 

It is assumed that it will work as follows:

  • Get the first image using animation, scroll it outside the field of view to the left (using the margin-left property)
  • Move the first image to the end (it actually deletes the image and creates a new one at the end).
  • Reboot the whole process.

I created the following function:

 function scroll() { var o = jQuery('.images').children().first(); var w = o.css('width'); var s = o.attr('src'); jQuery('.images:first-child').animate({'margin-left': "-"+w}, {'duration': 1000, 'complete': function(){ jQuery('.images').children().first().remove(); jQuery('.images').append("<img src='"+s+"' />"); scroll();}}); } 

Now it works as follows: the first image is animated correctly, then all of the following images do not scroll (the animation does not work), but after a time of 1000 ms the first image moves to the end. Thus, the images actually change, but the animation does not work.

I suppose the scroll() function at the end is called too early, but how to properly bind it?

+4
source share
1 answer

So, if I'm not mistaken, this is what you want to do:

Jsfiddle

The only difference you missed was to aim the images at it.

  jQuery('.images img:first-child') 
+4
source

Source: https://habr.com/ru/post/1498851/


All Articles