Header scrolling fixed jQuery code not working

Scrolling from top title fix doesn't work.

Snippet of code:

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 350) {
      $('.header-nav').addClass('fixed2');
    } else {
      $('.header-nav').removeClass('fixed2');
    }
  });
});
      

.fixed2 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: cornflowerblue;
}

html {
  min-height: 1000px;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-nav">
  <ul id="main-nav">
    <li><a href="index.html" class="active">Home</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="#">Register Your Business</a></li>
  </ul>
</div>
      

Run codeHide result


The jQuery code does not conflict, I used $

for jQuery.

jQuery doesn't work.

+3


source to share


1 answer


This code will help you.



$(document).ready(function () {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 50) {
                $('.header-nav').addClass('fixed2');
                $('.header-nav').css('top', Math.round($(this).scrollTop()) + 'px');
            } else {
                $('.header-nav').removeClass('fixed2');
            }
        });
    });
      

.fixed2 {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
    }
      

   

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
   <div class="header-nav">
        <ul id="main-nav">

            <li><a href="index.html" class="active">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="#">  Register Your Busi</a></li>
        </ul>
    </div>

    <div style="height:1000px;">&nbsp;</div>
      

Run codeHide result


-1


source







All Articles