I developed a snippet of jQuery script that dynamically adjusts the color of my navigation/header depending on the section of my website that the user is viewing. Although it functions, there are some imperfections. At times, it changes colors in the middle of a section when it shouldn't, or switches to the incorrect color for a particular section.
Below is the jQuery code I have implemented:
$( document ).ready(function() {
var top1 = $('#home').offset().top;
var top2 = $('#featuredWork').offset().top - headerHeight;
var top3 = $('#caseStudy').offset().top - headerHeight;
var top4 = $('#about').offset().top - headerHeight;
var top5 = $('#contact').offset().top - headerHeight;
//Alter header bar and elements' color based on the user's current section
$(document).scroll(function() {
if ($(document).scrollTop() >= top1 && $(document).scrollTop() < top2) {
$('#header').css('background-color', '#dadfe0');
$('.nav').css('color', '#21303f');
} else if ($(document).scrollTop() >= top2 && $(document).scrollTop() < top3) {
$('#header').css('background-color', '#21303f');
$('.nav').css('color', '#dadfe0');
} else if ($(document).scrollTop() >= top3 && $(document).scrollTop() < top4) {
$('#header').css('background-color', '#dadfe0');
$('.nav').css('color', '#21303f');
} else if ($(document).scrollTop() >= top4 && $(document).scrollTop() < top5) {
$('#header').css('background-color', '#21303f');
$('.nav').css('color', '#dadfe0');
} else if ($(document).scrollTop() >= top5) {
$('#header').css('background-color', '#dadfe0');
$('.nav').css('color', '#21303f');
}
});
});
This issue occurs on my incomplete portfolio website. Sometimes, the functionality works correctly upon the page loading, while other times it does not.
Check out my portfolio here
If anyone has any insights on why this behavior is inconsistent, I would greatly appreciate it!