Update the color of the Navigation Div once it has moved past a certain div

I am trying to update the color of my navbar-toggle from white to black or black to white.

The issue arises when it reaches a specific div with a class like 'white' or 'black'; the color changes as soon as the scroll starts.

var stickyOffset = $(".navbar-toggle").offset();
var $contentDivs = $("section");
$(document).scroll(function() {
    $contentDivs.each(function(k) {
       var _thisOffset = $(this).offset();
       var _actPosition = _thisOffset.top - $(window).scrollTop();
       if (_actPosition < (stickyOffset.top + $('.navbar-toggle').height()/2) && _actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
          $(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "white" : "black");
       }
    });
});

I have created a jsfiddle, but the change occurs too quickly and I'm unsure of what mistake I might be making.

http://jsfiddle.net/xarlyblack/8mn4bucw/

Thank you in advance! Best, Carl

Answer №1

I'm not sure if I've correctly understood your issue, but it appears to me that there might be a logic error in how you are assigning color labels. It seems like it should be done as follows:

...
if (_actPosition < (stickyOffset.top + $('.navbar-toggle').height()/2) &&
    _actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
          $(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black")
          .addClass($(this).hasClass("white") ? "black" : "white");
}
...

Furthermore, you can find an updated jsfiddle here where I believe the code is now functioning correctly.

Answer №2

Several users have already mentioned that in your jsfiddle, the two classes should be swapped. However, it seems like even on the initial page load, the classes do not match if, for instance, you have scrolled down and then reload/refresh the page or if you come from an anchor link.

To resolve this issue, I recommend running the class switch after the document has loaded as well:

var stickyOffset = $(".navbar-toggle").offset();
var $contentDivs = $("section");
$(document).scroll(function() {
    checkcolor();
});

$(document).ready(function() {
    checkcolor();
});

function checkcolor()
{
    $contentDivs.each(function(k) {
        var _thisOffset = $(this).offset();
        var _actPosition = _thisOffset.top - $(window).scrollTop();
        if (_actPosition < (30 + $('.navbar-toggle').height()/2) && _actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
            $(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "black" : "white");
        }
    });

}

I included a function call on document ready and removed the stickyOffset variable because upon reloading/refreshing the page, you are positioned in the middle of the site and the offset is off. Your stickyOffset should be a fixed value, so I added a default number of 30 instead.

Here's a fiddle link for reference: http://jsfiddle.net/5gcemfz0/3/

Answer №3

Looks like the issue is right here

$(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "white" : "black");

at this point. The logic states that 'if $(this) has class 'white' add 'white', otherwise add 'black'. It might be better to switch these around. Hope this solution works for you!

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

Discover the depth of a deeply nested array

I have a complex array structure that looks something like this: I am trying to determine the depth of this nested array, focusing on the element with the most deeply embedded children. let arr = [ { name: 'tiger', children: [{ ...

What's the best way to track changes in multiple form fields simultaneously in Angular?

Situation I have a form with 8 fields, but I want to monitor changes in just three of them to apply the same function. I don't want to set up individual subscriptions for each field like this: this.headerForm.get('start').valueChanges.subsc ...

How to send an email with an attachment using jQuery AJAX and PHP

I have developed a program for sending emails with attachments. Initially, I created it without using ajax and it worked perfectly fine. However, when I tried implementing jQuery ajax, the functionality stopped working. Upon clicking the apply button, noth ...

Steps to incorporate a session into an HTML login form

Need assistance with adding a session to my HTML form connected to MySQL database. The database updates whenever the page is reloaded or when a failed submission occurs. Can anyone provide a solution for this? <body> <?php // define variables a ...

Tips for sending an array from a higher-order component to a nested component in React Native using props

I have a scenario where I need to pass an array called "subjects" from the SubjectsScreen component to the MarkAttendanceScreen component and then display that array as a list using FlatList. Parent Component export default class SubjectsScreen extends C ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Should header and footer be incorporated as part of a template design?

Is it considered advisable to include tags such as etc from another page? For example: <?php include_once("header.php")?> Content specific to each individual page <?php include_once("footer.php")?> The header.php file includes: <!DOCTYP ...

Change `console.log` to output to a specified `div` container

I found a great example of using a simple rss feed parser on Stack Overflow. $.get('https://stackoverflow.com/feeds/question/10943544', function (data) { $(data).find("entry").each(function () { // or "item" or whatever suits your feed ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

Guide to routing all express pages to distinct pages (Without using the .html extension)

I have multiple pages stored in my static-content folder: index.html about.html dashboard.html Is there a way to route these pages without including .html in the URL? I'm looking for a solution that doesn't involve creating separate routes for e ...

What is the best way to organize a complicated array of arrays in JavaScript?

Within my code, there exists an array known as generationArray. Each array contained within generationArray consists of 252 elements. The first 250 elements serve as internal coding data, while the final two positions are designated for sorting criteria. T ...

Focusing on the content within an anchor tag while excluding the image

How can I prevent the picture from being underlined while ensuring that the hyperlink text remains underlined? The website is built on Wordpress theme, so I am restricted to using CSS only and cannot modify the HTML code. .post-desc a{ border-bottom ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

"JQuery encounters a parsing error while trying to process an XML

When I try to make an ajax request for an xml file, I encounter a parse error due to the presence of the xml declaration. Here is my AJAX request: <script> $(document).ready(function(){ $.ajax({ url: "/test/test.xml", ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

React: Should we use useCallback when creating a custom Fetch Hook?

Currently delving into the world of React on my own, I've come across this code snippet for a custom hook that utilizes the fetch() method. import { useState, useEffect, useCallback } from "react"; import axios from "axios"; funct ...

Having difficulty creating a simple HTML menu, where one button is visible but the other is unresponsive despite having identical CSS styling

Looking to enhance my HTML skills as a beginner, I've begun building a simple website and am currently focusing on the menu. I created a "home" button (which is visually there but not functional), and then attempted to create another button next to it ...

Optimal methods for arranging images in a list with CSS

I am trying to create a grid layout for a list of images using CSS. Here is the HTML code I have: <ul id='feat-products'> <li><img id='feat-product-1'></li> <li><img id='feat-product-2&apos ...

Why am I unable to view the image in the material-ui-next "Cards" example?

I came across this example on the material-ui-next website, but strangely I am unable to view the lizard image when I try to run it on my computer. Why is the image not showing? There are no errors in my console, and the "simple card" example on the websi ...