I have created a JQuery script that will highlight the 'About', 'My Projects', or 'Contact Me' text on the navigation bar when the corresponding section of the page is in view. To achieve this, I am using a scroll() event listener:
$(document).scroll(function myFuction() {
if ($(document).scrollTop() >= $("#contactMe").offset().top) {
$("#contactButton").addClass("active");
$("#projectButton").removeClass("active");
$("#aboutButton").removeClass("active");
} else if ( $(document).scrollTop() > $("#portfolio").offset().top && $(document).scrollTop() < $("#contactMe").offset().top) {
$("#contactButton").removeClass("active");
$("#projectButton").addClass("active");
$("#aboutButton").removeClass("active");
} else if ( $(document).scrollTop() > $("#about").offset().top && $(document).scrollTop() < $("#portfolio").offset().top) {
$("#contactButton").removeClass("active");
$("#projectButton").removeClass("active");
$("#aboutButton").addClass("active");
}
});
As the user scrolls, the function determines the position of the top of the page using scrollTop(), and then applies or removes the "active" class to highlight the appropriate text.
I am aware that performing actions within an event listener may not be the best approach, but I haven't found an alternative method yet. Perhaps I am trying to reinvent the wheel here?
I had hoped that the Bootstrap library would provide a predefined class for this functionality, but I have been unable to locate one so far.