Changing height of element on scroll triggers scroll event

1.6k Views Asked by At

I am adding a class to my header when the user scrolls down the page to reduce the height of the top part of the header and then as soon as they scroll back up I want to remove the class. This is working, but it's resulting in an issue where the class is being added and removed unexpectedly, I assume because the height change is triggering the scroll event to fire continuously.

$(function() {
  const $header = $('header');
  let prevScroll = 0;
  
  $(window).scroll(function() {
    let scroll = $(window).scrollTop();
    if (prevScroll - scroll > 0) {
      $header.removeClass('scrolled-down');
    } else {
      $header.addClass('scrolled-down');
    }
    prevScroll = scroll;
  });
});
.container {
  position:relative;
  width:90%;
  margin:0 auto;
}

header {
  position:sticky;
  top:0;
}
  .top-header {
    background:blue;
    height:50px;
    transition:all .5s;
  }
    header.scrolled-down .top-header {
      height:10px;
    }

  .nav-header {
    background:red;
    height:100px;
  }

.body-content {
  min-height:1500px;
  border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <header>
    <div class="top-header"></div>
    <div class="nav-header"></div>
  </header>
  <div class="body-content"></div>
</div>

1

There are 1 best solutions below

2
Ubaldo Suarez On

Yes it's cuz change the height of the element change your scroll position, so you need know the height of the header before and after scroll and then code your function. I think that you want to pin your small header at the top of the viewport when the user scroll to bottom so i think that the code below can help you

$(function() {
  const $header = $('header');
  let headerHeight = 160,
      headerSmallHeight = 60;
  
  $(window).scroll(function() {
    let scroll = $(window).scrollTop();
    //if no scroll = show the big header (remove the class)
    if (scroll === 0) {
      $header.removeClass('scrolled-down');
    //if scroll > the height of the big header then add the class
    } else if(scroll > headerHeight) {
      $header.addClass('scrolled-down');
    }
  });
});

I hope help you