I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows:
$(window).scroll(function () {
if ($(window).scrollTop() > 175) {
$('#location_menu').css('position', 'fixed').css('top','0px').css('z-index','1000');
$('.first').css('padding-top','415');}
else {
$('#location_menu').css('position', 'relative').css('z-index','1');
}});
However, the problem I am facing is that the scroll is not smooth, and when the element changes from position:relative to position:fixed, there is a noticeable jump of about 415px. This jump is equal to the height of the submenu.
Below is the CSS code for reference:
<div id="location_menu" >submenu content
</div>
<div id="content" class="location_detail first">content beneath submenu
</div>
I tried adding a line for .first
to set a padding-top of 415px when the page is scrolling and reaches within 175px of the top of the page .css('padding-top','415')
. However, this adjustment does not seem to be working correctly. There is no visible change, so it seems like I may have implemented it incorrectly.
Should I explore using a different scrolling function instead of the one listed above?
After some trial and error, I have modified the code based on the suggestion from @Danko. Here is the updated code:
$(window).scroll(function () {
var $conten = $('.first'),
$menu = $('#location_menu')
scrollpos = $(window).scrollTop();
if (scrollpos >= 175) {
$conten.css('padding-top','365px');
$menu.css('position', 'fixed').css('top','0px').css('z-index','1000');
} else {
$conten.css('padding-top','0');
$menu.css('position', 'fixed').css('position', 'relative').css('z-index','1');
}
});