Brad
Brad

Reputation: 202

Jquery scrollTop animation

I have an animation that needs to kick in once scrollTop() hits a given position on a page. That part is working fine, but what I want is for the animation to reverse when I scroll back up the page, returning the element to it's original position.

http://cdpn.io/dphBx

The code in my example is working fine and the JS is identical to the site I'm working on locally, but in Chrome the element doesn't return to it's original position when you scroll back up the page. JQuery is the only Javascript I'm linking to, so no conflicts, and there isn't anything in the CSS that should be preventing it either. I'm still pretty green when it comes to JQuery, so bear with me. I'm thinking maybe an if/else statement isn't the best way to accomplish this? Any thoughts?

Upvotes: 0

Views: 383

Answers (1)

Terry
Terry

Reputation: 66093

It works for me, using Chrome 31 on a Mac. However, you should try the following modifications to improve the performance:

  1. Use .stop(true, true) before chaining the animation, so that you ensure the animation goes to completion.
  2. Throttle or debounce the resize event so it is not fired too often, saving the number of calculations needed to be performed, and prevents quickly toggling between two animation end states too often.
  3. Get the scroll position with $(window).scrollTop() instead of on the body.

I have decided to use the jQuery throttle+debounce plugin available here: http://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js

$(document).ready(function(){
  $(window).scroll($.throttle(100, function(){
    var position = $("window").scrollTop();
    if(position >= 200){
      $("#foo").stop(true,true).animate({left: "200px"}, "fast");
    } else{
      $("#foo").stop(true,true).animate({left: 0}, "fast");
    }
  }));
});

Upvotes: 1

Related Questions