Nakib
Nakib

Reputation: 4703

Twitter Bootstrap 3 Navigation Menu Unexpected Behaviour

I am using twitter bootstrap for my site.The navbar link get active on click but i want same effect when i scroll to particular section of the page. i.e (links turns grey on click, i want same effect when i scroll on that section)

// jQuery code

$(document).ready(function() {

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 50
        }, 1000);
        return false;
      }
    }
  });
});


 $('.nav li a').on('click', function() {
      $(this).parent().parent().find('.active').removeClass('active');
      $(this).parent().addClass('active');
  });


});

I have tried using twitters scrollspy but because of this line of code scrollTop: target.offset().top - 50 i am having some problem. Example When i click on Contact it goes on contact section but portfolio link is active in navigation menu.

My Site: www.nakibmomin.com

Upvotes: 3

Views: 149

Answers (3)

Jake OS
Jake OS

Reputation: 190

Okay, do something like this:

  1. Add global function to detect element visibility (Ref):

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();
    
        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();
    
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
    
  2. Then attach scroll listener:

    $(window).scroll(function(){
    
      if(window.isScrolledIntoView('#portfolio')){
          $('.menu li').removeClass('active')
          $('[href="#portfolio"]').parent().addClass('active');
       }
    
    });
    

Upvotes: 1

user2721793
user2721793

Reputation: 84

Maybe there are better solutions, but it works.

$(document).scroll(function(){
    var ma = [];
    if(!$('html,body').is(':animated')){
        $('body>div[id]').each(function(i,o){
            ma.push({ i:$(o).attr('id'), p:$(o).position().top + $(o).outerHeight()});
        });
        for(m in ma){
            f = ma[m];
            if (f.p >= $(document).scrollTop()+$(window).height()/3){
                $('.menu>li.active').removeClass('active');
                $('.menu>li>a[href=#'+f.i+']').parents('li').addClass('active');
                break;
            }
        }
    }
});

Upvotes: 1

Justinas
Justinas

Reputation: 43479

Try apply offset of -60 for scrollspy, to apply offset too. From here

Upvotes: 2

Related Questions