I am making one big scroll page. And my nav is fixed positioned. I want to change the color (from black to white and vice versa) on the nav when it reaches specific sections on my page. It's because some of them are white, and some of them are dark - I want to make a contrast. I already made a class in css that should be toggled. But I am having difficulties using my code. Take a look at it:
https://jsfiddle.net/Lp27vuu4/
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
$('nav').toggleClass('light-mode',
//add 'light-mode' class when div position match or exceeds else remove the 'light-mode' class.
scroll >= $('.section2').offset().top
);
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed
body {
margin: 0px;
padding: 0px;
}
nav {
width: 100%;
position: fixed;
text-align: center;
padding-top: 20px;
padding-bottom: 20px;
}
.light-mode {
color: #fff;
}
.section1 {
width: 100%;
height: 400px;
background-color: #fff;
color: #000;
padding: 100px;
}
.section2 {
width: 100%;
height: 400px;
background-color: #000;
color: #fff;
padding: 100px;
}
.section3 {
width: 100%;
height: 400px;
background-color: #fff;
color: #000;
padding: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<h3>navigation links</h3>
</nav>
<section class="section1">
section 1
</section>
<section class="section2">
section 2
</section>
<section class="section3">
section 3
</section>
The conclusion:
My navigation by default is dark colored. When I reach the section that is dark I want to tell jQuery to add class .light-mode
to <nav>
. But when user goes off the section, I want it to go back to normal (so delete the class). In my solution it has issues:
- It seems to it is not going back to original when user is not on the section.
- The class is added just when user scrolls from top to bottom page. It looks on
.offset().top
. I want to make it more professional and universal. I want to add this class when each section is on screen not matter if its from bottom or top.