jqueryjquery-animate

Jquery animate by class, but set distance dynamically by each div's individual data attribute


I need to be able to chain a series of animations together via callback functions so that they execute precisely one after the other. However, several of these animations affect multiple divs at the same time (via shared class) and need to animate different distances (via indiviudal data attributes defined in each div). So I'd really like to just call one single animate event if possible to keep things simple.

The HTML looks like this:

<div class="gamepiece gamepiece2 tobedropped" id="g65" data-drop="150"></div>
<div class="gamepiece gamepiece3" id="g66"></div>
<div class="gamepiece gamepiece5 tobedropped" id="g67" data-drop="50"></div>
<div class="gamepiece gamepiece1 tobedropped" id="g68" data-drop="100"></div>

And I want to call a single Jquery animate which will move each div down by "data-drop" number of pixels, i.e. something like:

$(".tobedropped").animate({ "top": "+="+$(this).attr("data-drop")+"px"}, 650, function() {
     // callback function
     startNextAnimation();
});

Obviously the $(this) isn't working in this situation, but is there a way I can set that pixel drop amount dynamically based on each div's individual data-drop attribute value?

Thank you!


Solution

  • I think you have to loop through each element to animate them based on their properties.

    $(".tobedropped").each(() => {
        $(this).animate({ "top": "+="+$(this).attr("data-drop")+"px"}, 650, () => {
            if ($(".tobedropped:animated").length)
                startNextAnimation();
        });
    });