I want to remove / add classes when the user is at different distances from above using jQuery.
I did this successfully and it works great, but I think I am doing it wrong and I would like your help to optimize the code.
html is simple, mostly sections (including the header) are 100% wide. and different colors. I want the title to change color when it is above the first section (for aesthetic purposes). And I also want it to have a shadow when the page scrolls more than 1 pixel.
I do this by adding / removing classes.
When I use one else else if command, it does not work, because whenever any condition is matched, js stops checking for other matches, so it does not apply all the necessary classes.
The following code works, however, as I said, I think this is not optimal / poorly written. Here is the HTML markup:
<header class="dark no-shadow"> Header </header> <section class="blue"> Please Scroll Down to see the header changes... </section> <section> The header color Should change when you pass through me. </section>
And here is the jQuery code:
var header = $('header'), blueSection = $('section.blue'), // Calculate when to change the color. offset = blueSection.offset().top + blueSection.height() - header.height(); $(window).scroll(function(){ var scroll = $(window).scrollTop(); // Remove Class "dark" after scrolling over the dark section if (scroll >= offset) { header.removeClass('dark'); } else { header.addClass('dark'); } // Remove Class "no-shadows" whenever not on the top of the page. if (scroll >= 1) { header.removeClass('no-shadow'); } else { header.addClass('no-shadow'); } });
And for those of you who like to use jsfiddle (like me!): Https://jsfiddle.net/shock/wztdt077/6/
Thanks guys!
source share