Reputation:
I have developed a page, which has a fixed menu once the page is scrolled and also the tabs will become active on their appropriate section id's.
I have almost completed the functionality but I am facing some problems :
i have seen lot of demo's and tried but failed to implement. as per my knowledge i did this demo. Please help me out with the current code change where I have done wrong.
this is what I tried.
HTML:
<div class="top_layer">Top Layer</div>
<div class='menu'>
<ul>
<li><a href="#basic1">basic 1</a></li>
<li><a href="#basic2">basic 2</a></li>
<li><a href="#basic3">basic 3</a></li>
<li><a href="#basic4">basic 4</a></li>
</ul>
</div>
<div id="basic1" class="section">basic 1</div>
<div id="basic2" class="section">basic 2</div>
<div id="basic3" class="section">basic 3</div>
<div id="basic4" class="section">basic 4</div>
JS:
var menuSection = $('.section') , navLists = $('.menu ul li'),
navLists_height = navLists.outerHeight(), headerOffset = $('.top_layer').offset().top;
$(window).on('scroll', function () {
var window_top = $(window).scrollTop() + 12;
if (window_top > headerOffset) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
var cur_position = $(this).scrollTop();
menuSection.each(function() {
var top = $(this).offset().top - navLists_height,
bottom = top + $(this).outerHeight();
if (cur_position >= top && cur_position <= bottom) {
navLists.find('a').removeClass('active');
menuSection.removeClass('active');
$(this).addClass('active');
navLists.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
navLists.find('a').on('click', function () {
var $el = $(this)
, id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - navLists_height
}, 500);
return false;
});
});
Upvotes: 0
Views: 367
Reputation: 3124
I have update the code , check fiddle , your navlist selecting anchors should be outsideof window scroll.
var menuSection = $('.section'),
navLists = $('.menu ul li'),
navLists_height = navLists.outerHeight(),
headerOffset = $('.top_layer').offset().top;
$(window).on('scroll', function() {
var window_top = $(window).scrollTop() + 12;
if (window_top > headerOffset) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
var cur_position = $(this).scrollTop() + 70;//70 for fixed header height
menuSection.each(function() {
var top = $(this).offset().top - navLists_height,
bottom = top + $(this).outerHeight();
if (cur_position >= top && cur_position <= bottom) {
navLists.find('a').removeClass('active');
menuSection.removeClass('active');
$(this).addClass('active');
navLists.find('a[href="#' + $(this).attr('id') + '"]').addClass('active');
}
});
});
navLists.find('a').on('click', function() {
var $el = $(this),
id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - navLists_height
}, 500);
return false;
});
Upvotes: 1