简体   繁体   中英

Hide menu when scroll down and show when scroll up by using vanilla JavaScript

I have a navigation menu. This menu, I have build it with bootstrap and I want it to hide when scroll down and show when scroll up. I get the requirement to it by using vanilla JavaScript only.

Here is my HTML code :

<nav class="navbar navbar-default navbar-fixed-top  custom-header" >
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Menu</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a class="navbar-brand" href="" style="color:#FFF">
                    <img src="img/header-logo.png" alt="Happy Tour" />
                </a>
            </div>

            <!-- This section contains all link buttons in the header -->
            <div class="collapse navbar-collapse pull-right mybtn" id="bs-example-navbar-collapse-1" style="margin-top:9px;">
                <button class="btn btn-primary btn-md"><i class="glyphicon glyphicon-bookmark"></i> Destinations</button>
                <button class="btn btn-success btn-md"><i class="glyphicon glyphicon-th"></i> Tour Package</button>
                <button class="btn btn-danger btn-md"><i class="glyphicon glyphicon-file"></i> Book Ticket</button>
                <button class="btn btn-info btn-md"><i class="glyphicon glyphicon-search"></i> Find Hotel</button>
                <button class="btn btn-success btn-md"><i class="glyphicon glyphicon-user"></i> Register</button>
                <button class="btn btn-primary btn-md"><i class="glyphicon glyphicon-fire"></i> Login</button>
            </div>
        </div>
    </nav>

This is a css:

.custom-header{
     padding: 0;
     height: 120px;
     line-height: 120px;
     background: url(../img/top_head_bg.jpg) repeat-x;
     border:none;
}

Like suggested with this article Auto-Hide Sticky Header (I also used those 4 words to instantly find the solution in Google ) you can set your header as fixed

.header {
    width: 100%;
    height: 7.5em;
    position: fixed;
    z-index: 1000;
    top: 0;
    left: 0;
}

and then react to the scroll to change the top property with JS .

Good Luck'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM