Reputation: 9855
I have a function that positions a div depending on the webpages position.
function calcNav(){
var b = $('#breadcrumb').offset().top;
var w = $(window).scrollTop();
var x = b - w;
//console.log('breadcrumb from top = ' + b + ' window scrolled = ' + w + ' position of nav = ' + x);
$('.sub-nav').css('top', x);
}
calcNav();
$(window).scroll(calcNav);
The function works great, my only issue is that as its constantly rendering my page speed appears a bit laggy - is there any way I can run the function at the end of the scroll instead of during?
Upvotes: 0
Views: 1002
Reputation: 27765
I would recommend to you use it with combination with setTimeout
and add small amount of milliseconds:
var scrollTimeout;
$(window).scroll(function() {
clearTimeout( scrollTimeout );
scrollTimeout = setTimeout( calcNav, 50 );
});
clearTimeout
in this case is used to not trigger previous call if next scroll event was triggered less than 50ms, in case you think your users will scroll slower you can increase this value for example to 100ms etc.
Upvotes: 1