dunn_rite
dunn_rite

Reputation: 41

Keep navbar at top of page when scrolled to correct position

So with my website I have a header. At the top of the header I have my logo and slogan, and beneath that I have my nav bar. When the user scrolls down I want the top part of the header (logo and slogan) to disappear whereas the nav bar should stay fixed. I know this would need some position:fixed; added to it but how do I get it to activate only when it's in the right place. I've worked a bit with media queries before. Is there one for a y-scroll?

Thanks

Upvotes: 1

Views: 52

Answers (1)

Dmitry Ivanov
Dmitry Ivanov

Reputation: 381

You'll need to use javascript here in order to subscribe for window.onscroll event.

window.onscroll = function(){
    if(window.pageYOffset > 100/*px*/)
        $('.nav').addClass('fixed_bar');
    else
        $('.nav').removeClass('fixed_bar');
}

And css for .fixed_bar will be something like this:

.fixed_bar{
    position:fixed;
    top:0;
    z-index:10000;
}
.fixed_bar .logo{
    display:none;
}

Also, you'll have to account for a space that the fixed nav will free and add padding or margin to the beneath element;

Upvotes: 2

Related Questions