EZDC
EZDC

Reputation: 682

Nav show/hide on scroll

I am building a script to show/hide a navigation menu at a certain height on the page. It does work just that when I scale the page and the layout snaps to it's next state the scroll show/hide script still runs at the same height based on the width of the window at load.

Here is the code:

$(window).on('scroll', function(){
    if( $winwidth > 1200 ){
        console.log('over 1200');
        var $menudrop = 800;
        if( $(window).scrollTop() >= $menudrop ){
            $('#hidden-nav').slideDown(1000);
        }else{
            $('#hidden-nav').slideUp(1000);
        }
    }
});

$(window).on('scroll', function(){
    if( $winwidth < 1200 && $winwidth > 992  ){
        console.log("under 1200");
        var $menudrop = 560;
        if( $(window).scrollTop() >= $menudrop ){
            $('#hidden-nav').slideDown(1000);
        }else{
            $('#hidden-nav').slideUp(1000);
        }
    }
});

What am I not getting here?

Upvotes: 0

Views: 293

Answers (2)

jfriend00
jfriend00

Reputation: 707536

You will have to refresh the value of $winwidth before you using it because it's value may have changed due to resize events. There is generally no reason to maintain a global width value, so I'd suggest just changing it to a local variable like this that you simply get it whenever you need it.

$(window).on('scroll', function() {
    var $winwidth = $(window).width();
    if ($winwidth > 1200 ) {
        console.log('over 1200');
        var $menudrop = 800;
        if ($(window).scrollTop() >= $menudrop) {
            $('#hidden-nav').slideDown(1000);
        } else{ 
            $('#hidden-nav').slideUp(1000);
        }
    } else if ($winwidth < 1200 && $winwidth > 992  ){
        console.log("under 1200");
        var $menudrop = 560;
        if ($(window).scrollTop() >= $menudrop) {
            $('#hidden-nav').slideDown(1000);
        } else{
            $('#hidden-nav').slideUp(1000);
        }
    }
});

I'd also suggest you combine all your logic into one scroll handler since there's no reason to have two separate event handlers.

Upvotes: 1

Stephen Thomas
Stephen Thomas

Reputation: 14053

Well, you don't show us how you set $winwidth, but if it's set on page load, you'll need to update it on window.resize events.

Upvotes: 1

Related Questions