Phoenix
Phoenix

Reputation: 322

How to change the active class on scroll in bootstrap using jquery?

Its a landing page so all navigation link represent a section on same page.

My navbar

 <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand Name</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">            
            <ul class="nav navbar-nav navbar-right">
              <li class="active"><a href="#home">Home</a></li>  
              <li><a href="#about">About Us</a></li> 
              <li><a href="#choose">Why This Company</a></li> 
              <li><a href="#mission">Mission and Vision</a></li> 
              <li><a href="#services">Services</a></li> 
              <li><a href="#">How it Works</a></li> 
              <li><a href="#destination">Destination</a></li> 
              <li><a href="#associate">Associate Partners</a></li>             
              <li><a href="#contact">Contact Us</a></li> 
            </ul>
          </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
      </nav>

On click its changing the active class using jquery

        $(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li').removeClass('active');

        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
    });
});

I am not able to do it on scroll. Each nav link represents a section on that same page.

Thanks.

Upvotes: 1

Views: 2902

Answers (1)

Oleksandr  Maliuta
Oleksandr Maliuta

Reputation: 516

<div id="about"></div>
...

 $(window).on('scroll', function(event){
   var scrollPos = $(document).scrollTop();
   $(".nav li a").each(function () {
     var currLink = $(this);
     var refElement = $(currLink.attr("href"));

     if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
       currLink.parent().addClass("active").siblings().removeClass("active"); 
       return;
     }
     else{
       currLink.parent().removeClass("active");
     }
   })
 })

Upvotes: 0

Related Questions