Shrinking header on scroll 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() &gt; 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.
// 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() &gt; 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;
}
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset="utf-8"&gt;
  &lt;meta name="viewport" content="width=device-width"&gt;
  &lt;title&gt;&lt;/title&gt;
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" &gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="single-level-nav"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;