How do I get the top number that my animation is at the moment?

Asked

Viewed 54 times

1

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

I wonder how I get the number he’s currently on top before reaching the end?

Code:

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

css:
.cair{
  top: 0px;
}
  • You want this information while running the animation?

  • Yes, during the animation

1 answer

1


The method .animate() has a function Progress that can be called for this you want:

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

Example: http://jsfiddle.net/tL7Dm/

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

To get the top position has two ways:

  • read position/css every step top

Example: http://jsfiddle.net/hxx39/1/

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

Example: http://jsfiddle.net/hxx39/

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.