Reputation: 929
I have a website, it has a sticky nav placed at the bottom of a <header>
element, as long as I scroll to a section it actives a class using data-attributes
, the bug here is: when I scroll the class active
adds on the half of the section even the scroll does not scroll according to the section.
What I want is to turn on the active
class as long as I get the anchor of each section, I leave my code below followed by a jsfiddle you can see what is the problem, I hope you guys can help me.
The HTML:
<header class="testheader">
<nav id="cloud_nav" class="absolute">
<ul>
<li><a href="#" data-scroll="overview">Section 1</a></li>
<li><a href="#" data-scroll="readiness">Section 2</a></li>
<li><a href="#" data-scroll="collaboration">Section 3</a></li>
</ul>
</nav>
</header>
<section data-anchor="overview" style="background: red; font-size: 25px;">
</section>
<section data-anchor="readiness" style="background: green; font-size: 25px;">
</section>
<section data-anchor="collaboration" style="background: #ccc; font-size: 25px;">
</section>
</div>
Javascript:
<script type="text/javascript">
// Sticky Nav
$('#cloud_nav a').on('click', function() {
var scrollAnchor = $(this).attr('data-scroll'),
scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top;
$('body,html').animate({
scrollTop: scrollPoint
}, 500);
return false;
})
var navOffset = $('#cloud_nav').offset().top;
$(window).scroll(function(){
var scrollPos = $(window).scrollTop();
if (scrollPos >= navOffset){
$('#cloud_nav').removeClass('absolute');
$('#cloud_nav').addClass('fixed_cloud_nav');
$('section').each(function(i) {
if ($(this).position().top <= scrollPos - 50) {
$('#cloud_nav a.active').removeClass('active');
$('#cloud_nav a').eq(i).addClass('active');
}
});
} else {
$('#cloud_nav').removeClass('fixed_cloud_nav');
$('#cloud_nav').addClass('absolute');
$('#cloud_nav a.active').removeClass('active');
$('#cloud_nav a:first').addClass('active');
}
});
</script>
The Fiddle: http://jsfiddle.net/qfaeqo2w/
Thanks in advance, regards.
Upvotes: 1
Views: 532
Reputation: 3706
Is this what you were after?
First, I changed calculating the scrollPoint
to take into account the size of the header:
scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top - $('#cloud_nav').outerHeight();
Then, rather than subtract 50 pixels, we add the height of the nav where it's detecting the scroll position:
if ($(this).position().top <= scrollPos + $('#cloud_nav').outerHeight())
The anchors now scroll to the right place and the active classes look to be switched correctly.
Upvotes: 1