Alex Yap
Alex Yap

Reputation: 173

Sticky nav: Can't figure out why removeClass doesn't work when scrollTop is less than my nav's offset().top

I can't seem to figure out why removeClass doesn't work when my scrollTop is less than or not equal to my nav's offset().top value:

$(document).ready(function(){
    $(window).scroll(function(){
        var scrollPos = $(window).scrollTop();
        var targetPos = $("nav").offset().top;    
        console.log(scrollPos);    
        if ( scrollPos >= targetPos ) {
           $("nav").addClass("fixed-nav");
        } else {
           $("nav").removeClass("fixed-nav");
        }
   });
});

https://codepen.io/alexyap/pen/EmOPpd -> pen to my attempt

Upvotes: 1

Views: 161

Answers (2)

NIRAV PAREKH
NIRAV PAREKH

Reputation: 137

It's because your nav element might be at 0 position of page. The >= operator will always return true. Use only >.

Upvotes: 0

frnt
frnt

Reputation: 8795

Don't get your offset().top value during window.scroll for element nav instead get that on document.ready and try,

$(document).ready(function(){
  var targetPos = $("nav").offset().top;
  $(window).scroll(function(){
    var scrollPos = $(window).scrollTop();
    if ( scrollPos >= targetPos ) {
      $("nav").addClass("fixed-nav");
    } else {
      $("nav").removeClass("fixed-nav");
    }   
  });
});
* {
  margin: 0;
  padding: 0;
}

body {
  height: 3000px;
}

header {
  height: 100vh;
  width: 100%;
  position: relative;
  background: red;
}

nav {
  width: 100%;
  height: 80px;
  background: black;
  position: absolute;
  bottom: 0;
}

nav ul {
  margin: 0 auto;
  text-align: center;
  width: 100%;
}

nav ul li {
  list-style: none;
  display: inline-block;
}

nav ul li a {
  text-decoration: none;
  font-size: 24px;
  color: #fafafa;
  line-height: 80px;
  padding: 0 10px;
}

.fixed-nav {
  position: fixed;
  top: 0;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
  <ul>
    <li><a href="#">Test 1</a></li>
    <li><a href="#">Test 2</a></li>
    <li><a href="#">Test 3</a></li>
    <li><a href="#">Test 4</a></li>
  </ul>
</nav>
</header>

Upvotes: 2

Related Questions