1

I'm trying to change the color of an element depending on where you are on the site. I have liked it to one anchor point and it is working. But i want it to change color more than one time. Every time it reaches the anchor point #intro i want it to be white and when it reaches the anchor point #portfolio i want it to go black again. How can i make this work?

This is what i have so far:

function scroll_style() {
   var window_top = $(window).scrollTop();
   var div_top = $('#portfolio').offset().top;

   if (window_top > div_top){
      $('#nav-icon4 span').css({"background":"#000"});

   }
}
$(function() {
    $(window).scroll(scroll_style);
    scroll_style();
});
  • Have you tried else { $('#nav-icon4 span').css({"background":"#FFF"}); } after your if statement? – Lodder Oct 12 '15 at 16:41
  • Yes and that works fine when i scroll upp to #intro but when i continue to scroll down to next point #experience i also want it to go back to white and when i hit the las anchor point i want it to go black again and that doesn't work. – Sam Oct 12 '15 at 16:48
  • Could you provide a JSFiddle please? – Lodder Oct 12 '15 at 16:53
2

I'm not understanding the last anchor part, but to get it back to white after scrolling to next point, you have to compare against element bottom position too. And if not true, revert to white.

function scroll_style() {
   var window_top = $(window).scrollTop();
   var $element = $('#portfolio');
   var div_top = $element.offset().top;
   var div_bottom = div_top + $element.outerHeight();
   var $icon = $('#nav-icon4 span');

   if (window_top > div_top && window_top < div_bottom){
      $icon.css({"background":"#000"});
   }
   else{
      $icon.css({"background":"#FFF"});
   }
}
$(function() {
    $(window).scroll(scroll_style);
    scroll_style();
});
| improve this answer | |
0

That's way more complex than you need. Skip using JS logic and just use the CSS nth-child() Selector or nth-of-type() Selector.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.