简体   繁体   中英

Hide a div on scroll but keep it visible when active

I'm trying to hide the .site-header on scroll and have it re-appear after inactivity for a couple of seconds.

I found the most of the answer here: How to hide a Div when the scroll bar is moving with jQuery?

 var $header = $(".site-header"); var opacity = $header.css("opacity"); var scrollStopped; var fadeInCallback = function () { if (typeof scrollStopped != 'undefined') { clearInterval(scrollStopped); } scrollStopped = setTimeout(function () { $header.animate({ opacity: 1 }, "slow"); }, 500); } $(window).scroll(function () { if (!$header.is(":animated") && opacity == 1) { $header.animate({ opacity: 0 }, "slow", fadeInCallback); } else { fadeInCallback.call(this); } }); $('.menu-toggle').on('click', function(){ $('.menu-toggle').addClass('activated'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script> <section style="height:5000px;"> <div class="site-header" style="position:fixed; top:5px; left:5px; width:200px; height:100px; display:block; background:#000; opacity:1;"> <button class="menu-toggle">Menu</button> <nav class="nav-primary"> <ul> <li>Menu item 1</li> <li>Menu item 2</li> <li>Menu item 3</li> </ul> </nav> </div> </section>

The nav is activated by clicking button

However, the nav is nested inside the .site-header which means when the menu is activated it still fades out on scroll...

I'm wondering how to alter this javascript so that when the .activated class is applied to the button the nav remains visible even while scrolling.

Here is the fiddle https://jsfiddle.net/fwa16eok/

Thanks so much!

Add !$menu.is(":active") before the fade out animation call

 var $menu = $("#menu"); var opacity = $menu.css("opacity"); var scrollStopped; var fadeInCallback = function () { if (typeof scrollStopped != 'undefined') { clearInterval(scrollStopped); } scrollStopped = setTimeout(function () { $menu.animate({ opacity: 1 }, "slow"); }, 2000); } $(window).scroll(function () { if (!$menu.is(":active") &&!$menu.is(":animated") && opacity == 1) { $menu.animate({ opacity: 0 }, "slow", fadeInCallback); } else { fadeInCallback.call(this); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script> <section style="height:5000px;"> <div id="menu" style="position:fixed; top:5px; left:5px; width:200px; height:100px; display:block; background:#000; opacity:1;"></div> </section>

HTML:

<div>
   <div class="a">A</div>
</div>​

Javascript:

$(window).scroll(function() {  
   if ($(this).scrollTop() > 0) {
      $('.a').fadeOut();  } 
   else {
      $('.a').fadeIn();
 }
});

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