R Astan R Astan - 3 months ago 12
Javascript Question

Display issue with affix nav in mobile view

I have just finished a site for a garage, there is a header with nav under it, and on scroll the nav become fix at the top of the screen. Usually very simple and have had no problems doing this on other sites. However, on this particular project, if loaded on a mobile phone, 9 times out of 10 there is an issue with the nav jumping up on scroll, briefly leaving a white strip where the padding is added to the page to accommodate the new status of the nav which has jumped up early.

The site is http://telstargarage.com and no matter what I do, this site will not let me post the code, as it says it is not properly formatted, even if I follow the help, and it all looks sweet in the preview, it will not post, so please feel free to fork the site. Thanks

Answer

It's difficult to diagnose as you haven't posted any code.

I'm guessing your issue is here though:

$(document).ready(function () {
    var menu = $('.menu');
    // This is likely incorrect on document ready 
    var origOffsetY = menu.offset().top; 

    function scroll() {
        if ($(window).scrollTop() >= origOffsetY) {
            $('.menu').addClass('navbar-fixed-top');
            $('.scrolled').addClass('menu-padding');
        } else {
            $('.menu').removeClass('navbar-fixed-top');
            $('.scrolled').removeClass('menu-padding');
        }
    }

    ...

}

I suggest going about this a different way. Perhaps by changing the offset you're comparing it to to the offset of a container of the menu. That gets around the issue of resizing screens causing the original offset calculation to be incorrect too. Something like this

<div class="menu-container">
    <div class="menu">
        // Your menu in here
    </div>
</div>

With JS like this:

$(document).ready(function () {

    function scroll() {
        if ($(window).scrollTop() >= $('.menu-container').offset().top) {
            $('.menu').addClass('navbar-fixed-top');
            $('.scrolled').addClass('menu-padding');
        } else {
            $('.menu').removeClass('navbar-fixed-top');
            $('.scrolled').removeClass('menu-padding');
        }
    }

    ...

}
Comments