0
\$\begingroup\$

I have the following jQuery which applies a class to my fixed header to shrink it when the user is scrolled any distance down the page:

$(window).scroll(function() {
if ($(this).scrollTop() > 1){
    $('div.single-level-nav').addClass("shrunk");
  }
  else{
    $('div.single-level-nav').removeClass("shrunk");
  }
});

This is working, but of course is constantly firing whenever the user is scrolling. This seems a bit of overkill, and not a great use of resources.

What I have may be the best way of achieving what I want, but I was wondering if there was a better way.

\$\endgroup\$
3

1 Answer 1

1
\$\begingroup\$

// init your element
var $nav = $('div.single-level-nav');
// use a boolean var to check if the element is already shrinked
var navShrinked = false;

$(window).on('scroll', function() {
  if ($(this).scrollTop() > 1){
    // add class only once
    if(!navShrinked) {
      $nav.addClass("shrunk");
      navShrinked = true;
    }
  }
  else{
    // remove class only once
    if(navShrinked) {
      $nav.removeClass("shrunk");
      navShrinked = false;
    }
  }
});
body {
  height: 1500px;
}
.single-level-nav {
  height: 100px;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #000;
  transition: height .3s;
}
.single-level-nav.shrunk {
  height: 50px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
</head>
<body>
<div class="single-level-nav"></div>
</body>
</html>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.