Reputation: 410
I've been trying to write a very simple animated sticky side bar using jQuery and its animate() function to change the top: CSS property of a div. Unfortunately in everything but chrome, it can get very laggy. I'm assuming its filling the memory every time the window scrolls and it calculates a newTop. Is there a better way to do this?
$(function() { // document ready
var $sticky = $('.sticky');
var stickyTop = $sticky.offset().top;
var padding = 0;
var stickyMargin = parseInt($sticky.css('margin-top')) + padding;
var intersection = stickyTop - stickyMargin;
$(window).scroll(function(){
var windowTop = $(window).scrollTop();
if (intersection < windowTop) {
var newTop = (windowTop - intersection);
$sticky.stop().animate({top: newTop}, 'slow');
}
else if ($sticky.offset().top != 0) {
$sticky.stop().animate({top: 0}, 'slow');
}
});
});
Upvotes: 2
Views: 109
Reputation: 5410
The problem that I see is that every scroll action creates a animation which is queued in the render pipeline of your browser. You will need to debounce the animation, so you dont get an animation stack that makes the whole thing extremly buggy. For example you could wait a few milliseconds will the scroll is effectively registered. Have a look at jQuery Timeout. After that you can use it by editing the scroll() function in your script by
$(window).scroll(function(){
$.doTimeout( 'scroll', 300, function(){
// do your animation
});
});
Upvotes: 1