0

I'm trying to make a site with a fixed navbar. The navbar will have a transparent background. I want to make the color of the text in the navbar to change based on the section of the site the user is looking at.

Let's say that the site starts by loading into a white page. The text in the navbar should start off by being black so that the user is able to read the text.

The user then scrolls to the next part of the webpage. Let's say that this part of the page is black. The text in the navbar should be white so that the user is able to read the text.

How do I do this? Do I need to use an event listener?

  • This is really impossible for us to answer since we have no idea what controls the color.... – epascarello Jul 24 '18 at 03:00
  • I feel like you are more interested in what part of the page is visible VS what the user is physically looking at with his eyes. There is a clear distinction and usecase for each one. Could you maybe elaborate your question more? – MSB Jul 24 '18 at 03:05
  • You would need to calculate the scroll distance to the next section you think needs a navbar color change, then have an onscroll event that checks if the widow offset is between that scroll distance and the next section that should have a color change, and apply the new styling accordingly. – SamVK Jul 24 '18 at 03:06
  • A more common example of this is with simply underlying the current section the user it as on a one-page website. You can probably find some code example of that (but in your case, instead of underlying, change the text color). Here's on example of that (albeit using JQuery): https://stackoverflow.com/questions/9979827/change-active-menu-item-on-page-scroll – SamVK Jul 24 '18 at 03:09

1 Answers1

0

(function($) {
  $(window).on('scroll', function() {
    if ($(this).scrollTop() > 200) {
      $('#stick').addClass('black-text');
    } else {
      $('#stick').removeClass('black-text');
    }
  });
})(jQuery);
body {
  margin: 0;
  padding: 0;
}
#stick {
  position: fixed;
  top: 2px;
  left: 2px;
  color: #fff;
}
#stick.black-text {
  color: #000;
}
#black {
  width:100%;
  height: 200px;
  background-color: #333;
}
#white {
  width:100%;
  height: 800px;
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="stick">Sticked Menu</div>
<div id="black"></div>
<div id="white"></div>

Assuming the height of each part is not dynamic, you may try this solution and see if this is what you need...

Chaska
  • 3,165
  • 1
  • 11
  • 17