My goal is to make the menu bar stick to the top of the viewport once the header has been scrolled past.
To achieve this, I have used jQuery and implemented the following code to adjust the CSS when the menu bar reaches the top:
jQuery(document).ready(function($){
// Check the initial position of the Sticky Header
var stickyHeaderTop = $('#stickyMenu').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#stickyMenu').css({position: 'fixed', top: '0px'});
$('#stickyAlias').css('display', 'block');
} else {
$('#stickyMenu').css({position: 'static', top: '0px'});
$('#stickyAlias').css('display', 'none');
}
});
});
You can view my development page with a working example here:
While this functionality works perfectly in Firefox, there seems to be an issue in Chrome. The CSS change occurs earlier than expected - the menu bar becomes fixed after scrolling just a few pixels. I suspect that the header image may be causing this problem, but I'm unable to pinpoint the exact reason...
EDIT:
Thank you for all your suggestions. Since I am currently away from my development setup, I will need to review all the suggestions at a later time. As mentioned by Explosion Pills and Malk, the issue stems from the fact that the stickyHeaderTop
is calculated before the header image is fully loaded. This explains why it works once the image is cached, but not on a page refresh.
I will test out Explosion Pills' solution(s) later and upvote/accept as needed.