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!