I want to transition the background colour of a fixed header element on scroll. So as a user scrolls down a full page block website, the header subtly changes to complement the block colours. I have almost achieved this on a Pen, however I can't quite work out how to measure how much has been scrolled as a flag for when to change.
Some extra info: The scroll amount to change at is 400px. The background colours are stored and fetched in an array. For reference my jQuery code is below:
$(document).ready(function(){
var bgArray = ["#252525","#333333","#454545","#777777"];
var scrollHeight = 400;
var scrolled = $(window).scrollTop(); //What is this measuring?
$(window).scroll(function() { //Can these conditions be neatened into one function?
if(scrolled < scrollHeight) {
$('header').css('background', bgArray[0]);
}
if(scrolled > scrollHeight) { // i.e more than 400px
$('header').css('background', bgArray[1]);
}
// and so on (800, 1200...)
})
})
Please refer to the Pen for full code. Any suggestions are greatly appreciated!
Updated Solution (2019)
To set a
background
for theheader
based on the current block in view below theheader
while scrolling:because
header
has fixed position, we can get the amount by which window has scrolled by using$header.offset().top
,(index of the current block in view) is the ratio of (the amount by which window has scrolled) to the (height of each block),
now adjusting for the height of the
header
, the index of the current block in view isMath.floor(($header.offset().top + headerHeight) / sectionHeight)
.See simplified demo below:
Original Solution
Check the
top
of eachblock
with respect to how much the window has been scrolled (scrollTop
) using$(window).scrollTop() > $('.block-1').offset().top
. So now we can use this to change color on entering the block - see demo below:Note that this solution needlessly loops through the sections on each scroll update called by the browser - and I don't like the look of it.
you are using scrolled as a fixed variable you should use it directly in your condition
this will make it dynamic for all elements inside wrap div
Try Like this:
This is current scroll, so it should be inside:
$(window).scrollTop()