1

I have this navigation for mobile that i want to hide/show depending on which direction the viewport gets scrolled in. So if scrolling down i want it to hide, and scrolling up i want it to show.

My current code looks like this. It just toggles on scroll top. Anyone?

$(function() {
    $(window).on("scroll touchmove", function () {
        $('.mobile-nav').toggleClass('tiny', $(document).scrollTop() > 0);
    });
});
user2952238
  • 749
  • 2
  • 11
  • 36
  • Found the solution here: http://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event – user2952238 Dec 09 '14 at 14:53

1 Answers1

0

Maybe something like this:

var menu_height = 80;
var menu_visible = true;
var old_scroll = $(window).scrollTop();

function checkMenu() {
    new_scroll = $(window).scrollTop();
    if (old_scroll < new_scroll && new_scroll > 0) {
        // Scroll down
        if (menu_visible == true) {
            toggleMenu();
        }
    } else if (old_scroll > new_scroll) {
        // Scroll up
        if (menu_visible != true) {
            toggleMenu();
        }
    }
    old_scroll = new_scroll;
}

function toggleMenu() {
    if (menu_visible == true) {
        // Hide
        $('#menu').animate({top: '-='+menu_height+'px'}, 200, function(){ $(this).css('display', 'none') });
        menu_visible = false;
    } else {
        // Show
        menu_visible = true;
        $('#menu').css('display', 'block').animate({top: '+='+menu_height+'px'}, 200);
    }
}

$(document).ready(function() {
    // Show / hide menu on scroll
    setInterval(checkMenu, 100);
});

Codepen: http://codepen.io/anon/pen/dPGggg

Lutsen
  • 153
  • 1
  • 11
  • Thank you! Question, how could i make it so the menu also shows when there is no scrolling going on? e.g when the scrolling is idle. – user2952238 Dec 10 '14 at 10:19
  • 1
    @user2952238 You could use `setInterval` to toggle the menu after a certain time if it's not visible. But as a user experience, I don't think this is a good idea. I think the user should be in control, and this way he is not, because the menu shows when you (the designer) thinks it should, not when the user asks for it (by scrolling up). You could add a "scroll to top" button, or a "show the menu" button. – Lutsen Dec 11 '14 at 09:27