I use the following javascript to make a 'sticky' navigation, which makes the nav fixed to the top of the screen when the user has scrolled past it. This code works fine, although when the element is made sticky and the position of the element is set to 'fixed', the position of all of the following elements in the body 'jump up' to occupy the gap created from changing the element from relative to fixed, and makes a slight 'jolting' effect. To counter this, I have tried adding an offset to the scroll y position when the element is changed to fixed, but this causes a loop by triggering the scroll function again, and the page scrolls to the bottom of the page.
So my question is - how in the function below can I add an offset to the scroll position? ie, how can I set the scroll position in the $(window).scroll function, without triggering the $(window).scroll function into a loop?
$(window).scroll(function (event) {
var y = $(this).scrollTop();
var top = $('#main-navigation').offset().top;
if (y >= top) {
$('#navigation').addClass('fixed');
}
else {
$('#navigation').removeClass('fixed');
}
});
Any help is very much appreciated
event.preventDefault()to stop the execution of the default scroll behavior of window. also, could you make a Fiddle where we can see the issue?