Reputation: 12487
This is my current code: http://jsfiddle.net/spadez/9sLGe/3/
I am concerned that it will be very laggy doing this because it's monitoring scroll
. I saw mention on my other question of debouncing a bit like this:
var scrollTimeout,
callback = function () {
/// Do your things here
};
$(window).scroll(function () {
if (scrollTimeout)
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(callback, 40);
});
Can anyone tell me if this is a good idea and how it might be integrated.
James
Upvotes: 4
Views: 6449
Reputation: 5994
For smooth results, I would stick with this firing on every scroll event. Otherwise there would be a delay before sticking or unsticking.
However, you can improve the performance of your function by caching the jQuery collections, and only sticking / unsticking if needed.
Here's a simple example module using your code: http://jsfiddle.net/9sLGe/9/
(function() {
var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $('#select').offset().top;
$window.scroll(function() {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
console.log("fixed");
} else if (currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');
console.log("unfixed");
}
});
}());
Upvotes: 5
Reputation: 324630
The main issue is not really one of rapid-firing events (although debouncing will certainly help, at the cost of a slight lack of responsiveness/immediateness), but more of one that you are changing CSS properties every single time the event fires.
You should consider having a flag like "isStickified", and use your if
condition to change that flag. If, and only if, the flag changes, that is when you should set the CSS to update. This will be much more efficient.
Upvotes: 4