简体   繁体   中英

Adding a Javascript listener that triggers when an element has a certain Y position

Is there a way to add a listener that triggers a function when an element is at a certain y-position?

On click, I have an element animating up with jQuery.

During that animation, the elements y-position will reach 0 (and go past it). When it reaches 0, I'd like to trigger another function that displays a different .

I've been trying to read about event management with anonymous event handling but have been unable to figure out how to get it working. Thank you!

if your animation was from say 50 to -10, you could split it up into 2 animations. 50 to 0, and 0 to -10. That would give you the opportunity to call your function when the first animation completes, and wouldn't have the overhead of checking position on each step.

You can use step option of animate method which is fired at each step of the animation. Here you can check for the y-position of the element and trigger the required event.

$(element).animate({
  height: '50%'
},
{
  step: function(now, fx) {
     //Here check the y-position of the element and then call the required function
     if($(fx.elem).offset().top == 0){
        //Code here
     }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM