Twitter Bootstrap 3 Navigation Menu Unexpected Behavior
I am using twitter bootstrap for my site. The nav link is clickable, but I want the same effect when I navigate to a specific section of the page. ie (links are greyed out on click, I want to get the same effect when I scroll through this 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 tried using twitters scrollspy but because of this line of code scrollTop: target.offset (). top - 50 I'm having problems. Example When I click Contact, it goes to the contact section, but the portfolio link is active in the navigation menu.
My site: www.nakibmomin.com
+3
source to share
3 answers
There may be 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;
}
}
}
});
+1
source to share
Ok, do something like this:
-
Add a global function to detect element visibility ( Link ):
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)); }
-
Then attach a scroll listener:
$(window).scroll(function(){ if(window.isScrolledIntoView('#portfolio')){ $('.menu li').removeClass('active') $('[href="#portfolio"]').parent().addClass('active'); } });
+1
source to share