My page contains four sections, each set to 100% height with different background color. At the very top I have a fixed menu. I want the menu to change it's background color depending on which section the user is at the moment, so it blends better with the background.
So far I have managed to make the menu's bg color to change when portfolio is entered, but it's not much and I am stuck. It has to change it's color again, when the user scrolls back to home, forth to about and so on. Also, I want it to be animated, but I don't know how to use animate() with addClass(). I've been trying for the past two days with no success at all.
The other thing that tortures me is that the menu elements should respond to the scroll position too. For example, if the user scrolls from Home to Portfolio, the active class should be applied to Portfolio and removed from Home. Hope you got the idea.
So far my code looks like this:
<div class="menu">
<div id="menu-center">
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a class="inactive" href="#portfolio">Portfolio</a></li>
<li><a class="inactive" href="#about">About</a></li>
<li><a class="inactive" href="#contact">Contact</a></li>
</ul>
</div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>
I have no idea why, but I can't post the css here without breaking the whole post, so just go to jsFiddle to see it all together.
$(document).ready(function () {
var menu = $('.menu');
var portfolio_position = $('#portfolio').offset().top;
var about_position = $('#about').offset().top;
var contact_position = $('#contact').offset().top;
$(window).scroll(function () {
var scroll = $(this).scrollTop();
if (scroll >= portfolio_position) {
menu.removeClass('menu').addClass('menu-light');
}
});
});
See this: http://jsfiddle.net/Dxtyu/1/
a slightly different approach is to check if the element is actually in view. I based this solution on a great little function provided here: https://stackoverflow.com/a/488073/1807551 by Scott Dowding. You can easily set colors/classes for each div section using this technique.
Solution fiddle: http://jsfiddle.net/acturbo/YzM3Q/
CSS:
jquery:
Try this fiddle. I've assigned a different class to each div so you can see the transitions more easily.
Included the animations(from this SO question), using this:
Added a new class to target the divs for hover.
Then for change event and class replacement, this jquery:
Scroll with this:
HTH!
Here: JSnippet DEMO
Using:
And: