Attempting to dynamically alter the background color of a sticky header once a specific class reaches the top of the viewport

I am in need of a solution to alter the background color of a simple sticky header whenever a div/class/id reaches the top of the window, and revert back when scrolled up. This change should occur multiple times.

The base code for the sticky header can be found here: https://jsfiddle.net/wzrfg2xe/1/

Below is the HTML Code:

<div class="sticky-element-positioner">
<div class="sticky-element">
<nav class='greedy-nav'>
<ul class='visible-links'>
<li><a href='#'>Menu 1</a></li>
<li><a href='#'>Menu 2</a></li>
<li><a href='#'>Menu 3</a></li>
</ul>
</nav>
</div>
</div>

<section class="one"> blabla</section>
<section class="two"> blabla</section>
<section class="three"> blabla</section>
<section class="four"> blabla</section>
<section class="five"> blabla</section>

CSS

ul { margin: 0; }
.greedy-nav {
height: 40px;
position: relative;
min-width: 250px;
width: 100%;
background: #513e5d;
width: 100%;
text-align: center; }

.greedy-nav a {
display: block;
padding: 0 30px;
line-height: 40px;
font-size: 16px;
color: #ddd;
text-decoration: none; }

.greedy-nav a:hover { color: #fff; background: rgba(0,0,0,.1); }

.greedy-nav .visible-links { display: inline-table; }
.greedy-nav .visible-links li { display: table-cell; }
.greedy-nav .visible-links li:first-child { font-weight: bold; }
.greedy-nav .visible-links li:first-child a { color: #fff !important; }

.sticky-element,
.sticky-element-positioner {
height: 40px;
text-align: center;
width: 100%;
z-index: 5; }

.sticky-element { position: static; }

.sticky-element.sticky-element-sticky {
position: fixed;
left: 0;
top: 0;
margin: 0; }

.sticky-element-positioner { position: static; }

.one { background: green; height: 300px; }
.two { background: yellow; height: 300px; }
.three { background: red; height: 300px; }
.four { background: blue; height: 300px; }
.five { background: orange; height: 800px; }

JS

$(document).ready(function() {

var stickyElement = $('.sticky-element'),
stickyElementPositioner = $('.sticky-element-positioner');

function stickyElementFixed() {
stickyElement.addClass("sticky-element-sticky");
}

function stickyElementStatic() {
stickyElement.removeClass("sticky-element-sticky");
}

$(window).scroll(function() {
var elementTarget = (stickyElementPositioner.offset().top);
var scrollTop = $(window).scrollTop();

if (scrollTop <= elementTarget) {
stickyElementStatic();
} else {
stickyElementFixed();
}

});

});

I came across a potential solution on Stack Overflow that can be viewed here: jsfiddle.net/8onnaqL7/ (from this post).

Combining these solutions led me to this revised version: http://jsfiddle.net/tpuqtobo/

However, it seems that the new implementation has removed the styling of the sticky header entirely. I have tried various approaches to resolve this issue but without success.

If there are alternative methods to achieve both the sticky behavior and color changes, I would greatly appreciate any suggestions or insights on how to address this challenge.

Thank you in advance for your assistance!

Answer №1

Your JavaScript code that utilizes the `removeClass()` function is currently removing all classes, including the `greedy-nav` class, leading to navigation issues.

Instead of only adding the `project-x` class, consider using the following code:

$(".greedy-nav").removeClass().addClass("greedy-nav project2");

Here is a working example on JSFiddle: http://jsfiddle.net/tpuqtobo/1/

I hope this solution proves helpful. Thank you!

Answer №2

Give this a shot:

$(".greedy-nav").removeClass().addClass("greedy-nav project1");

All classes, including greedy-nav, were removed so they need to be added back for proper CSS styling.

Answer №3

To accomplish this effect using only CSS, make sure to include the following code:

.sticky-element.sticky-element-sticky .greedy-nav {
    background: red;
}

Instead of just adding:

.sticky-element.sticky-element-sticky {
    background: red;
}

This is necessary because the main background header styling relies on the .greedy-nav element.

Is this information helpful for you?

Answer №4

To implement a scrolling effect in your website, utilize the scroll method.

Below is a sample code snippet with fully functioning code:

$(document).ready(function () {
    $(document).on("scroll", onScroll);  
    
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");
        
        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
      
        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
        }
        else{
            currLink.removeClass("active");
        }
    });
}
/* Add your CSS styles for the menu here */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="m1 menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#Menu1">Menu1</a>

            </li>
            <li><a href="#Menu2">Menu2</a>

            </li>
            <li><a href="#Menu3">Menu3</a>

            </li>
            <li><a href="#Menu4">Menu4</a>

            </li>
        </ul>
    </div>
</div>
<div id="Menu1"></div>
<div id="Menu2"></div>
<div id="Menu3"></div>
<div id="Menu4"></div>

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

Troubleshooting: Dealing with undefined index error in PHP when using $_GET with Ajax

For a school assignment, I am developing a social media platform that includes a basic chat feature. Each friend connection has its own conversation thread. The problem arises when reloading all the chat messages using Ajax. I encounter difficulty in retr ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

The module 'pouchdb' appears to be missing, functioning correctly on Mac but encountering issues on Windows

I have taken over a project built with Ionic that was originally developed on a Mac by my colleague. I am now trying to run the project on my clean Windows 10 PC with Ionic, Cordova, and Python installed. However, I am encountering an error that my colleag ...

Having difficulty selecting a nested ul with CSS, I'm currently exploring different options

For the website I am working on, I have a cms system that is responsible for rendering menus. My current task involves selecting the children of the parent menu items, and here is how the code is being generated: <div class="menu"> <ul> ...

Manipulating text alignment and positioning in CSS

Can someone help me achieve this CSS result? img1 This is what I have so far: img2 I'm struggling to center the elements and add a line in CSS. Any advice? I thought about using margin: auto, but I'm not sure if that's the best approach ...

ReactJS - Unable to access property of undefined object

I encountered a TypeError when rendering, stating that my object is not defined. Despite thinking I defined it before using it. Here is an example of ArticleDetails.js that I am referencing: import React, {Component} from 'react'; class Arti ...

Create a dynamic table using an array in jQuery

Currently, my goal is to generate a table using an array with the following format: [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: &ap ...

Can a nested array be divided into two separate arrays in Javascript?

I have received an array structured like this var cars = [['BMW'],[],['6000cc']]; This array includes two distinct values of the same item. The presence of an empty array indicates a change in data. The data on the left side of the e ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Executing a curl POST request within an npm script

I recently added a new script to my npm scripts in the package.json file, but I'm running into issues due to the single and double quotes. The problem seems to be with the internal double quotes within the payload. "slack": "curl -X POST --data-urlen ...

Leveraging the power of JavaScript's .map(...) method in a

Within my React code, I have a structure similar to the following: {elements.map((element) => { return ( <div> {renderDate(element.date)} </div> ) }})} This structure calls the renderDate function defined as: co ...

How can I customize the color of the cross in the hamburger menu?

Seeking guidance for a technical issue I'm facing. The problem lies with the X button on the menu - although everything seems to be in order, I encounter an error when attempting to change its color to black. If anyone has insight or advice on how I c ...

ways to display divs horizontally

Hello, I am trying to display these columns horizontally, but they are currently showing up vertically. How can I change this? Here is the blade file code snippet: <div class="col-lg-3 mb-4"> <!-- Input & Button Groups --> ...

What steps should I take to address the issue of receiving a "TypeError: Cannot read property 'toString' of undefined"?

Here is the HTML code: <div class="my-3"> <label for="quantity">Quantity:</label> <a class="minus-cart btn"><i class="fas fa-minus-square fa-lg" id="{{cart.product.id}}" ></ ...

Repositioning elements within the web browser

I am looking to create a web page that features: a variety of objects with distinct shapes (such as squares, rectangles, and more) the ability for users to connect these objects using arrows (see image link below) Furthermore, users should be able to mo ...

Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges: 1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, ...

Can you display names in capital letters from the randomUser.me API?

Apologies if this is not the appropriate platform for my query. Just to provide context, I am a designer with minimal experience in APIs and Javascript. I am currently utilizing the randomUser API to create a JSON file or URL that can be integrated into I ...

What is the best way to incorporate blade syntax into jQuery when using Laravel's Ajax functionality?

I am currently working on a code that deletes records of results after the foreach statement, and I am trying to figure out how to apply blade grammar to jQuery. <table class="table table-hover"> @if(Auth::check() && ...

Firestore - Safely removing a large number of documents without running into concurrency problems

I've encountered issues with my scheduled cloud function for deleting rooms in a Firestore-based game that were either created 5 minutes ago and are not full, or have finished. Here's the code I'm using: async function deleteExpiredRooms() ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...