Skip to content Skip to sidebar Skip to footer

Menu Items Getting Highlight As I Scroll To Each Section With Deficiency

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

Solution 1:

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:

  1. The last item is not getting highlighted.
  2. When clicking on a menu item, the page scrolls to the respective section but that menu doesn't get highlighted unless scrolling down the page a little bit.

Problem 1

This one is easy, you just forgot to add the id attribute to the last section :)
It should be:

<section id="contact" class="container contact-us section">  

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 the offset().top of the element).

So, following the code you have included, it will be something like:

if (position + my_margin >= target) {

The margin could be the height of your navigation bar:

my_margin = $('#site-navigation').height();

You can, obviously, add a little more or less to tailor it to your needs.


Solution 2:

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:

var position = $(this).scrollTop() + $(window).height;

Post a Comment for "Menu Items Getting Highlight As I Scroll To Each Section With Deficiency"