I just used this code to get my menu highlighted as I scroll down to each each section of my WordPress site:
(function($) {
$(document).ready(function(){
$("header nav ul").toggleClass("open");
$("section.container").addClass("section");
});
$(window).scroll(function() {
var position = $(this).scrollTop();
$('.section').each(function() {
var target = $(this).offset().top;
var id = $(this).attr('id');
if (position >= target) {
$('#primary-menu > li > a').removeClass('active');
$('#primary-menu > li > a[href=#' + id + ']').addClass('active');
}
});
});
}(jQuery));
css:
.active{
color: #fff !important;
}
Here is the link: http://scentology.burnnotice.co.za Problem is that the last item(Contact) is not getting highlighted when I scroll all the way down up to contact section. Also,if I click on a menu item,it goes to the respective section but that menu doesn't get highlighted unless I scroll the page a little bit down'. How can I solve that? Thanks in advance
NOTE: It seems that you took that code from my answer to this SO question, I have edited it to cover your case. Other people looking for more code can check it out for a snippet.
So, you have two problems:
Problem 1
This one is easy, you just forgot to add the
id
attribute to the last section :)It should be:
Problem 2
Your click event starts a scroll animation to the corresponding section but, since the navigation bar is on the top of the page, you made the animation to leave a little margin on the top. That margin prevents the section from reaching the top of the page, so the menu item doesn't get highlighted.
@Shnibble pointed you in the right direction, you can add a small positive margin to the value returned by
$(window).scrollTop()
(or a negative one to theoffset().top
of the element).So, following the code you have included, it will be something like:
The margin could be the height of your navigation bar:
You can, obviously, add a little more or less to tailor it to your needs.
There is a simple solution and it just requires a bit of additional math :)
You are measuring from the top of the
(window)
viewport and checking to see if it is greater than or equal to the top of a specified target div. Because your content sections are exactly 100% of the viewport, it is impossible for the top of the viewport ever be greater than or equal to the top of the last content div.What you need to do is offset the point you are measuring from so that you are not measuring from the top of the viewport, but rather some ways down from the top, say halfway or 3/4 of the way down. This will solve both of your issues.
Edit: here is something to get you started, then play around with dividing the window height by 1/2 or something like that: