简体   繁体   中英

hide menu on scroll down then show the menu when the scroll up reach 0 [javascript] not working for me

I've got a problem when I'm trying to create a menu effects... I've got this javascript code from the other and paste into my code but sad to say doesn't work for me and i don't know what is the reason..

here is my code

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>NMSC</title>
<link rel="stylesheet" type="text/css" href="css/global.css">
<script type="text/javascript" src="js/nav-slide.js">
</head>

 <body>
 <nav class="nav-main">
 <div class="logo">Website</div>
 <ul>
    <li><a href="#" class="nav-item">Home</a></li>
    <li><a href="#" class="nav-item">Library System</a></li>
    <li><a href="#" class="nav-item">Rules & Regulation</a></li>
    <li><a href="#" class="nav-item">Service Hours</a></li>
    <li><a href="#" class="nav-item">The Library</a></li>
</ul>
</nav>

<div class="big-wrapper">
<header>
    <h1>NMSC Online Library</h1>
</header>

</div>
</body>
</html>

css

.nav-main {
z-index: 99;
position: fixed;
width: 100%;
background-color: #222;
height: 50px;
color: #fff;

box-shadow: 5px 4px 5px #333333; 
-webkit-box-shadow: 5px 4px 5px #333333; 
-moz-box-shadow: 5px 4px 5px #333333;
}

javascript for the menu

$(window).scroll(function () {
    var d = $('.big-wrapper'); 
    if (d.offset().top < 400) {
       $('.nav-main').fadeIn();       
    } else {
       $('.nav-main').fadeOut();
    }
});

thanks...

and now I've got what the problem it is.. when i do this on javascript file..

alert('hello');

javascript popup when i reload the page then when I do this..

$(window).scroll(function () {
 alert('hello');
});

then scroll.. nothing happen..... i also tried to paste your answer on plain scratch but its seems the same.. nothing happen.

You are checking the position of a static element (d, which is .big-wrapper). If you want to hide your floating menu, then you should do like this:

$(window).scroll(function () {
var d = $('.nav-main'); 
if (d.offset().top < 400) {
   $('.nav-main').fadeIn();

} else {
   $('.nav-main').fadeOut();
      }
});

First of all, connect jquery library:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Now, you should get body scroll postion, and verify if it is lower than needed value (400 in your case). This should be done when document is "ready" . Here is the fiddle: http://jsfiddle.net/h06zpy12/1/

$( document ).ready(function() {    
    $(window).scroll(function () {     
        if ($('body').scrollTop() < 400) {
           $('.nav-main').fadeIn();

        } else {
           $('.nav-main').fadeOut();
        }
    });
 });

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