I am trying to create a navigation bar that sticks to the top of the screen after some scrolling. I followed two different tutorials but I can't seem to make either of them work properly.
The first tutorial does not stick to the top of the screen at all. The second tutorial does stick to the top of the screen, but if you scroll down far enough, you can't see the navigation until after it sticks to the top.
This is what I have right now (following the first tutorial):
var n = $("#nav-bar");
ns = "nav-bar-scrolled";
hdr = $('#nav-bar').offset().top;
$(window).scroll(function(){
if($(this).scrollTop() > hdr){
n.addClass(ns);
}else{
n.removeClass(ns);
}
});
This is the JS code following the second tutorial:
$(function(){
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('header').height();
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#nav-bar').css({position: 'fixed', top: '0px'});
$('#stickyalias').css('display', 'block'); //this doesn't do anything
} else {
$('#nav-bar').css({position: 'static', top: '0px'});
$('#stickyalias').css('display', 'none'); //this doesn't do anything
}
});
});
Full code here: https://jsfiddle.net/linahsie/rhp65j2b/2/ Thank you!