Skip to content Skip to sidebar Skip to footer

Change Colour Of Fixed Text Based On Underlaying Colours

I have a fixed menu that scrolls on top of both light and dark backgrounds. If the text is white it becomes invisible when on top of white elements. I would like to find a way wher

Solution 1:

You can use jQuery to add/remove a css class depending on the height of the divs.

Like this:

HTML:

<nav>
    link
    </nav>

    <div id="element1">
    </div>

    <div id="element2">
    </div>

    <div id="element3">
    </div>

CSS:

.wrapper {
  height: 100px;
}

nav {
  position: fixed;
  width: 100%;
  color: white;
  text-align: center;
 }

#element1 {
  height: 50vh;
  background-color: gray;
}

#element2 {
  height: 20vh;
  background-color: white;
}

#element3 {
  height: 100vh;
  background-color: black;
}

.active {
  color:black;
}

jQuery:

$(document).ready(function() {
$(window).scroll(function() {
   var element1height = $( "#element1" ).height(); 
   var element2height = $( "#element2" ).height();
   var total = element1height + element2height;
   var st = $(this).scrollTop();
   if( st > element1height ) {
   $("nav").addClass("active"); 
   } 
   else {
   $("nav").removeClass("active"); 
   }
   if( st > total ) {
   $("nav").removeClass("active"); 
   } 
  }); 
 }); 

You can use jQuery to get the height of the divs - if the user scrolls past the height of <div id="element1">, it will add a class to <nav> which changes the color of the text within. If the user scrolls past the sum of <div id="element1"> & <div id="element2">'s height - it will remove the class.

JSFiddle Demo

Post a Comment for "Change Colour Of Fixed Text Based On Underlaying Colours"