Search code examples
jquerycssdrupal-7

JQuery: Get scroll position on page refresh


I have nav bar that becomes fixed when you scroll to it. The nav bar works perfectly. However, I also have a secondary nav bar that opens up below the primary nav. The secondary nav becomes fixed when the primary nav is scrolled to.

When a page is refreshed on my website, the scroll position before the refresh is maintained. If I refresh the page half-way down, and attempt to open my secondary nav, it is not visible. I've found the the fixed positioning is removed from the secondary nav upon refresh. However, if you scroll up or down from your scroll position, the code reads the scroll position, and applies the fixed positioning.

I'm a JQuery newbie, so I don't know exactly what I need to fix this issue. I'm open to suggestions. I think I need to get the scroll position upon refresh. Then I can apply the logic to keep the fixed positioning on the secondary nav from being removed.

$(window).scroll(function() {                  // assign scroll event listener
	
	    var s = $("#primary-nav");
		var pos = s.position();     // get current position
		$(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        //s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        if (windowpos > pos.top) {
            $('#secondary-nav').css({
	            position: 'fixed',
	            top: '60px',
	            zIndex: '505',
	        });
        } else {
            $('#secondary-nav').css({
	            position: 'static',
	        });
    });


Solution

  • I would try putting all that code in a function then calling that function on a scroll event and initially on page load.

    function navScroll(){
        
        var s = $("#primary-nav");
        var pos = s.position();     // get current position
        var windowpos = $(window).scrollTop();
        
        //s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        if (windowpos > pos.top) {
            $('#secondary-nav').css({
                position: 'fixed',
                top: '60px',
                zIndex: '505',
            });
        } else {
            $('#secondary-nav').css({
                position: 'static',
            });
        }
    }
    
    $(window).scroll(function() {
        navScroll();
    });
    
    $(document).ready(function() {
        navScroll();
    });