I am trying to add a class to the header when an element reaches the top of the viewport but I cannot seem to find out why it is not working. I have no errors and I have checked to see that jquery is fetching the offsets and it is. Any help would be great. I would also like to know how to extend this code to any number of section's rather than stating just 6.
$(document).ready(function () {
var project1 = $('section:nth-child(1)').offset();
var project2 = $('section:nth-child(2)').offset();
var project3 = $('section:nth-child(3)').offset();
var project4 = $('section:nth-child(4)').offset();
var project5 = $('section:nth-child(5)').offset();
var project6 = $('section:nth-child(6)').offset();
var $window = $(window);
$window.scroll(function () {
if ($window.scrollTop() >= project1) {
$("header").removeClass().addClass("project1");
}
if ($window.scrollTop() >= project2) {
$("header").removeClass().addClass("project2");
}
if ($window.scrollTop() >= project3) {
$("header").removeClass().addClass("project3");
}
if ($window.scrollTop() >= project4) {
$("header").removeClass().addClass("project4");
}
if ($window.scrollTop() >= project5) {
$("header").removeClass().addClass("project5");
}
if ($window.scrollTop() >= project6) {
$("header").removeClass().addClass("project6");
}
});
});
The method
.offset()
, returns an object containing the propertiestop
andleft
:Therefore you need to access the
top
property in your conditional statements.Change
to:
Updated Example
As a side note,
$('section:nth-child(1)').offset()
will be undefined because the section element isn't the first element (the<header>
is). Use:nth-of-type
rather than:nth-child
. Since you're using jQuery,eq()
would work too.