How do I get the top number that my animation is currently in?

1

I have a JavaScript animation that goes from top: 0px in CSS and by jQuery animation it goes to top: 385px which is where the animation ends.

I would like to know how I get the number that it is currently in top before it reaches the end?

Code:

$(function() {
$(".cair").animate({
  top:"+=385px",
},{
  duration: 6000,
  "complete" : function() {
  $('.cair').remove();
}
});
});

css:
.cair{
  top: 0px;
}
    
asked by anonymous 25.05.2014 / 21:01

1 answer

1

The .animate() method has a progress function that can be called to do this:

$(function () {
    $(".cair").animate({
        top: "+=385px",
    }, {
        duration: 6000,
            "complete": function () {
            $('.cair').remove();
        },
        progress: function (a, p, r) {
            //usar como quiser aqui
        }
    });
});

Example: link

According to the documentation, the progress function has 3 parameters. The second one passes the percentage where the animation is. The third is the number of milliseconds remaining until the animation is finished. This function was added in version 1.8

To get the top position there are two ways:

  • read at each step the position / css top

Example: link

    progress: function (a, p, r) {
        console.log(this.style.top);
    }
  • use the percentage to do the "where do you expect to be" accounts

Example: link

    progress: function (a, p, r) {
        var valorAtual = p * (fim - inicio);
        if (Math.round(valorAtual) == 200) alert('chegámos aos 200px!');
    }
    
25.05.2014 / 21:14