0

I need to create header on bottom and make it fixed on top when user scrolling.

Why when I scrolling fixed header is blinking?

It's bit of code:

$(document).scroll(function () {
 var bodyTop = $('body').scrollTop();
 var navOffset = $('.main-nav').offset().top;
 $('.main-nav').toggleClass('header-fixed', (bodyTop > navOffset));
});
.wrapper { height: 99000px; }
.header-fixed { 
      position: fixed !important; top: 0 !important; 
      bottom: none; background: yellow !important; }
 .main-nav { width: 100%; height: 72px; position: absolute; bottom:0; background: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <nav class="main-nav">
    </nav>
</div>

https://jsfiddle.net/u3kk219d/

mik01aj
  • 11,928
  • 15
  • 76
  • 119
Frunky
  • 385
  • 1
  • 6
  • 14

1 Answers1

3

I've moved the calculation of the element's offsetTop OUTSIDE the scroll, it only needs to be calculated the once. By doing this, it isn't messing with weird calculations every time you scroll, and it fixes the flicker.

var navOffset = $('.main-nav').offset().top;

$(document).on("scroll", function() {
  var bodyTop = $('body').scrollTop();
  $(".main-nav").toggleClass("header-fixed", (bodyTop > navOffset));
});
.wrapper {
  height: 99000px;
}

.header-fixed {
  position: fixed !important;
  top: 0 !important;
  background: yellow !important;
}

.main-nav {
  width: 100%;
  height: 72px;
  position: absolute;
  bottom: 0;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <nav class="main-nav">
  </nav>
</div>
Snowmonkey
  • 3,716
  • 1
  • 16
  • 16