I'm adding a few new features into a friend of mines website, which is already built. He wants a a div, which is a little bit bellow the header, to be locked to the screen as soon a the user scrolls to the top of it. I created the function bellow which works just fine, but as soon as jquery places the element in a fixed position, all of the elements bellow it slide up causing the entire site to "jump". Is there a way to prevent this from happening without placing all of these elements in an absolute position? This website is pretty involved and will take a lot to redo all of these elements.
jQuery(function($) {
function lockelem() {
if ($(window).scrollTop() > 786)
$('.tabs').css({'z-index': '10000', 'position': 'fixed', 'top': '-200px', 'width': '100%'});
else
$('.tabs').css({'position': 'relative', 'top': 'auto'});
}
$(window).scroll(lockelem);
lockelem();
});
Any suggestions would be greatly appreciated!
The previous answer is almost correct. It won't quite work because the else statement won't hide the placeholder div in time. You need this:
function lockelem() {
if ($(window).scrollTop() > $('#tabs').position().top ) {
$('#tabs').css({'z-index': '10000', 'position': 'fixed', 'top': '0', 'width': '100%'});
$("#tabPlaceholder").show();
}
if ($(window).scrollTop() < $('#tabPlaceholder').position().top ) {
$('#tabs').css({'position': 'relative', 'top': 'auto'});
$('#tabPlaceholder').hide();
}
}
lockelem();
$(window).scroll(lockelem);
Working fiddle, you may need to resize the window to make it small enough to show it working: http://jsfiddle.net/rlouie/j7hsX/