user3550879
user3550879

Reputation: 3469

Animate menu on scroll event

I am using the following code to create a hide/show nav

based on http://jsfiddle.net/mariusc23/s6mLJ/31/

my code

  var didScroll;
  var lastScrollTop = 0;
  var delta = 5;
  var navbarHeight = $('nav').outerHeight();

$(window).scroll(function(event) { didScroll = true; });

 setInterval(function() {
if (didScroll) {
  hasScrolled();
  didScroll = false;
}
 }, 250);

 function hasScrolled() {
   var st = $(this).scrollTop();
if (Math.abs(lastScrollTop - st) <= delta)
  return;

if (st > lastScrollTop && st > navbarHeight ) {
  // Scroll Down
  $('nav').removeClass('nav-down').addClass('nav-up');
} else {
  // Scroll Up
  if (st + $(window).height() < $(document).height()) {
    $('nav').removeClass('nav-up').addClass('nav-down');
  }
}
lastScrollTop = st;
}

However I want it to animate up when the user scrolls up OR down and then animates back when they are done scolling

Upvotes: 0

Views: 124

Answers (1)

Miro
Miro

Reputation: 8650

It could be much simpler that that.

For example:

var didScroll;

$(window).scroll(function(event) { didScroll = true; });
setInterval(function() {
  if (didScroll) {
      $('header').removeClass('nav-down').addClass('nav-up');
      didScroll = false;
  }else{
      $('header').removeClass('nav-up').addClass('nav-down');
  }
}, 400);
body {
    padding-top: 40px;
}

header {
    background: #f5b335;
    height: 40px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

.nav-up {
    top: -40px;
}

main {
   background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
   ) repeat;
    height: 2000px;
}

footer { background: #ddd;}
* { color: white}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="nav-down">
    This is your menu.
</header>
<main>
    This is your body.
</main>
<footer>
    This is your footer.
</footer>

Upvotes: 1

Related Questions