Change background of fixed header when scrolling past elements
Solution 1
Try this :
var t = $('#about').offset().top - 100;
var t1 = $('#work').offset().top - 100;
$(document).scroll(function(){
if($(this).scrollTop() > t1) {
$('header').css({"background-color":"blue"});
} else if($(this).scrollTop() > t) {
$('header').css({"background-color":"green"});
} else {
$('header').css({"background-color":"#520833"});
}
});
And so on with var t2 = ...
.
Don't forget to put higher values on top of the if
's
Solution 2
You could simplify things a bit by using jQuery's .each() method like this:
$(window).scroll(function () {
$('.sect').each(function () {
var w = $(window).scrollTop();
var t = $(this).offset().top - 100;
if (w > t) {
$('header').css({
"background-color": $(this).css('background-color')
});
}
});
});
From the documentation:
The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.
Dale Irwin
Updated on June 05, 2022Comments
-
Dale Irwin almost 2 years
I'm trying to get the background-color of my fixed header to change upon scrolling over certain DIV sections on the page, similar to this:
The sections I'm using don't have a fixed height.
I've found this similar question Change background-color while scrolling
( which uses this fiddle http://jsfiddle.net/cEvJk/18/ )
var t = $('#about').offset().top - 100; $(document).scroll(function(){ if($(this).scrollTop() > t) { $('header').css({"background-color":"green"}); } });
But I'm unable to get the effect to repeat for all sections.