Barbora
Barbora

Reputation: 41

Hide Menu on scroll down show on scroll up - issue with Safari

I have an issue with JS - "hide menu on Scroll Down, Show on Scroll Up" and its optimalization on Safari.

The menu works on all browsers except Safari where it disappears on the top because of the top bounce.

Here is the JS code:

var lastPosition = 0;
$(document).ready(function(){
  $(window).on('scroll', function(){

    $('header').toggleClass('hide', $(window).scrollTop() > lastPosition);
    lastPosition = $(window).scrollTop();

});

I dont want fixed menu I would be glad to hear any suggestions.

Thank you very much,

Barbora

Upvotes: 4

Views: 1223

Answers (1)

PatricNox
PatricNox

Reputation: 3918

I believe this issue is caused by an too-early effect, meaning it tries to hide the menu too early. Review the following code for example:

var hasScrolled;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    hasScrolled = true;
});

// Check condition every 250ms
setInterval(function() {
    if (hasScrolled) {
        hasScrolled();
        hasScrolled = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();
    
    // Make sure they scroll more than delta, which may fix Safari scenario
    if (Math.abs(lastScrollTop - st) <= delta)
        return;
    
    // If they scrolled down and are past the navbar, add class .nav-up.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }
    
    lastScrollTop = st;
}

the magic here, is that it checks whether if you've scrolled below the delta value before trying to hide the menu.

Credit: Gill @ codeseek.com (Source)

Upvotes: 2

Related Questions