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){

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.


1 Answer 1


// 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) {
      navShrinked = true;
    // remove class only once
    if(navShrinked) {
      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>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
<div class="single-level-nav"></div>


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.