Damian Zawadzki
Damian Zawadzki

Reputation: 33

Velocity.js - stopping animation callback

I have this code:

$(window).scroll(function () {
    if ($(this).scrollTop() > ($animate.headline.height() + 100)) {
        $animate.header.velocity({height: "50px"}, { queue: false });
    } else {
        $animate.header.velocity({height: "100px"}, { queue: false });
    }
});

If user scrolls xxx pixels from top then animation should start, and that works just fine.

One thing I just noticed and it bothers me - every time I scroll, velocity animation is checking that scrollTop, so overall animation isn't smooth when I'm scrolling, because before animation is triggered function is checking scroll.

Is there any other way to make it smooth?

Example:

http://codepen.io/anon/pen/bIkqF

Upvotes: 1

Views: 2394

Answers (2)

Patsy Issa
Patsy Issa

Reputation: 11293

Would you prefer a CSS approach instead?

Set your header's css to :

-webkit-transition: all 0.5s;
position:fixed;
top:0;
left:0;

Add a new class for the desired height:

.shrink{
    height:50px;
}

And in you js toggle the class :

var header = $('.header');
  $(window).on('scroll', function () {
      if ($(this).scrollTop() > (header.height() + 20)) {
          header.addClass('shrink');
      } else {
          header.removeClass('shrink');
      }
  });

Tinker with the seconds property of transition for a smoother effect.

This way the GPU does the heavy lifting and class toggles performance hit is negligible. Demo

Upvotes: 3

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

You should throttle your check with some library like Ben Alman's one : https://raw.githubusercontent.com/cowboy/jquery-throttle-debounce/v1.1/jquery.ba-throttle-debounce.min.js.

Check this documentation page : http://benalman.com/projects/jquery-throttle-debounce-plugin/.

For your example, you can use it like this :

$(window).scroll($.throttle(250, checkTop));

function checkTop() {
    if ($(this).scrollTop() > ($animate.headline.height() + 100)) {
        $animate.header.velocity({height: "50px"}, { queue: false });
    } else {
        $animate.header.velocity({height: "100px"}, { queue: false });
    }
}

Upvotes: 0

Related Questions