Reputation:
I'm using jquery to highlight my navbar when it passes certain points on my page, but there is one part where the nav isn't being highlighted until it passes below the object. The specific offender is the contact portion of the page.
here is the codepen - http://codepen.io/Davez01d/pen/NxMzYy?editors=0010
here is the relevant html -
<hr id="contact-anchor" class="line section-seperator">
css -
.on-section {
background-color: #2766af !important;
color: white;
}
.on-section:focus {
color: white;
}
and javascript -
$(window).scroll(function() {
var navHeight = $(".navbar").outerHeight();
var scrollTop = $(window).scrollTop();
var aboutPoint = $('#about').offset().top;
var lineMargin = parseInt($('.section-seperator').css('marginTop'));
var portfolioPoint = $('#portfolio-anchor').offset().top;
var contactPoint = $('#contact-anchor').offset().top;
if (scrollTop < aboutPoint) {
$('#home-btn').addClass('on-section');
$('#about-btn').removeClass('on-section');
} else if (scrollTop > aboutPoint && scrollTop < (portfolioPoint - navHeight)) {
$('#home-btn').removeClass('on-section');
$('#about-btn').addClass('on-section');
$('#portfolio-btn').removeClass('on-section');
} else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint) {
$('#about-btn').removeClass('on-section');
$('#portfolio-btn').addClass('on-section');
$('#contact-btn').removeClass('on-section');
} else if (scrollTop > (contactPoint - navHeight)) {
$('#portfolio-btn').removeClass('on-section');
$('#contact-btn').addClass('on-section');
}
});
Upvotes: 3
Views: 75
Reputation: 5764
Your updated pen is here. There was a problem in the calculation or better conditions when you switch the buttons:
} else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)) {
// in this condition you stick too long, you forgot the navHeight
} else if (scrollTop > (contactPoint - navHeight)) {
// therefore you reach this too late
}
In the first condition here you need to add the navheight:
} else if (scrollTop > (portfolioPoint - navHeight) &&
scrollTop < (contactPoint - navHeight))) {
// like this it works
} else if (scrollTop > (contactPoint - navHeight)) {
// and here we go...
}
Upvotes: 0
Reputation: 2896
To highlight the about
you do this
if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)
You have to quit the .navbar
height (just how you are doing in the others)
if (scrollTop > (portfolioPoint - navHeight) && scrollTop < (contactPoint - navHeight))
Here you have your codepen working http://codepen.io/anon/pen/XXoLWM?editors=0110
Upvotes: 0
Reputation: 36511
Making this change fixes the issue for me, I think you are forgetting that you are treating scrollTop
as the scrollTop + navbar height
var scrollTop = $(window).scrollTop() + navHeight;
Upvotes: 2