I recently came across a jQuery script for sticky navigation that I've implemented on a website.
$(function() {
// get the initial top offset of the navigation
var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
// determine whether the navigation bar should have "fixed" css position or not
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop();
if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':-23, 'left':0 });
} else {
$('#sticky_navigation').css({ 'position': 'relative', 'top':-30 });
}
};
sticky_navigation();
$(window).scroll(function() {
sticky_navigation();
});
});
Unfortunately, the script only functions smoothly if I do not resize the browser after loading the site. When I resize, the script does not account for the new size and the navigation bar moves to different positions while scrolling. I attempted to add
$(window).resize(function() {
sticky_navigation();
});
but it did not resolve the issue.
It seems like updating the top offset after a resize is necessary. Since I am not well-versed in programming, any suggestions with code examples would be greatly appreciated.
I hope someone can provide assistance.
EDIT: Link to example on jsfiddle: http://jsfiddle.net/p9Lvbz68/8/