Utilizing jQuery for altering the navigation color is yielding inconsistent outcomes

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!

Answer №1

Unfortunately, I am unable to test this for you, but my hunch is that the issue lies in storing the offsets in variables. By using the following code:

var top1 = $('#home').offset().top;

The value is saved in top1, however, this does not create a reference, meaning that the variable will not update when the offset changes.

Currently, you are utilizing

$(document).ready(function() { });
, which only ensures that the code within will not run until the DOM is loaded (your HTML). It does not wait for images to load. Considering that the offset changes when images load, the value stored in top1 may become invalid. It is possible that you are experiencing inconsistent results because sometimes the document ready executes after image loading (making it seem like it's working), and other times it runs before images are loaded (thus appearing as though it's not functioning).

A potential solution would be to retrieve the offsets directly within your document scroll function instead of relying on stored variables. (Alternatively, you could keep your variables inside the document scroll function.) For example:

if ($(document).scrollTop() >= top1 && $(document).scrollTop() < top2)

can be replaced with:

if ($(document).scrollTop() >= $('#home').offset().top && $(document).scrollTop() < ($('#featuredWork').offset().top - headerHeight))

Another option is to switch from using document ready to window load. The window load function will wait for all images to finish loading.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The SharePoint 2010 standard model dialogs seamlessly blend transparent printing with the background content

When using Sharepoint 2010, each list item you edit will open in a new modal dialog box by default. This dialog box appears as a new div with the class of ms-dlgContent. It also creates a div with the class of ms-dlgOverlay which acts as a grey overlay di ...

Internet Explorer 11's default document view mode now automatically switches to Edge viewing

I currently have Windows 7 and IE 11 installed on my local machine as I work on an ASP.NET, C# web application that utilizes Bootstrap, jQuery, and more. Recently, I implemented a checkbox dropdown list using the code from this link: . However, when view ...

Showcase fullcalendar events that span across multiple rows and columns

Within my Angular application, I am utilizing the Angular UI Calendar in conjunction with Fullcalendar to display user events. Currently, when a user interacts with an event by clicking on it, only a portion of the event is highlighted. This becomes probl ...

Strategies for maintaining a sticky element while transitioning between containers

My challenge involves a sticky button located inside a container, but the sticky behavior only seems to work within another element that is full width (container-fluid). Is there any way to make the sticky behavior global? I have attempted using 'fix ...

Margin not being applied to last element in parent - any ideas why?

Why does the margin of the last element, whether it is a <p> or <h1>, not have any impact? It should be pushing the background of the parent container downwards. .container { background: grey; } h1 { margin-bottom: 3em } p { margin- ...

Utilize jQuery to implement validation on the newly added form

I created a form with fields for first name, last name, and email. I've implemented a code that allows users to add another person with the same three fields when they click a button, and this function works perfectly. Additionally, I have added requ ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

Switch up the URL and redirect by employing jQuery

Looking for a solution in jQuery to redirect based on user input? <form id="abc"> <input type="text" id="txt" /> </form> If you want to redirect to a URL constructed from the value of the text box, you can try this: var temp = $("#tx ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

Open up a new window and block Google Analytics from tracking

Currently, I am facing a challenge with integrating another company's Google Analytics code into our system. Although I have a basic understanding of the code, I lack substantial experience. The specific code segment in question is aimed at tracking ...

Create custom styles for Android applications using CSS or themes programmatically

As I work on developing an application, I am interested in implementing a unique approach... To retrieve a CSS file from the server and apply it to the activity layout. To create a string file for styling or theming and integrating it into the layout. I ...

Troubleshooting Problems with CSS Before Selector and Margins

Currently, I am attempting to utilize the before selector in order to replicate some list item behavior for elements. Due to constraints where I cannot use list items, it is crucial that I find a way to make styles work effectively. If you would like to s ...

Sub menus are not appearing in the drop-down menu

Below is the code for my dropdown button with an additional level. Initially, the button works as intended. However, upon attempting to click within the dropdown submenu, I noticed that all four items displayed the same last submenu only. .icon-cadet-l ...

Ways to bypass a transition using JavaScript

Hello everyone, I would like to start by apologizing for any mistakes in my English. I have been working on a website, which is currently available here: As you scroll down, the height of the image below the menu decreases. I am trying to make the navig ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

Two nested divs positioned below text within a parent div

I am styling a content div with text and two child divs positioned next to each other within the content div. My goal is to have the child divs display below the text, rather than beside it. body { text-align: center; } #first, #second { border: so ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

"Implementing a jQuery dialog box that sends JSON response to a different page rather than the current

Currently, I am working on an MVC application where I need to insert properties of certain objects. To achieve this, I have created a modal popup using jQuery dialog. In order to avoid any interference with other user actions, I have implemented an Ajax.Be ...

Refresh the div element's HTML and content using AJAX

I am interested in implementing a feature similar to the StackExchange link found on the top left of the Stack Overflow site. From what I gather, when the stack exchange link is clicked, the following actions take place: The hidden div container becom ...