Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Change CSS on scroll

Hello,

I have a problem and I'll try to explain it to you as best as I can.

I have section with dark photo that takes 100% of screen size, below that one I have pretty light website. I have navigation menu fixed on top of that 100% section and I want it to change color and stay fixed when I scroll down from that section.

I hope I wasn't too confusing.

Thank you for your help

3 Answers

Yes this needs some javascript to listen to the scroll and compare current position to your tracked elements. My approach (if not using a plugin), is to initialize an event listener object..and then you can just do whatever when it hits those events.

See quick example here: http://codepen.io/cjm771/pen/xohBd

//on dom load we initalize the changeMenuColor operation
//now we just need to listen for the evemt amd do whatrever
$(function(){
   changeMenuColor.init();
   $("#p1").on("isOnElement.changeMenuColor", function(){
     console.log("im on page 1");
     $(".menu").removeClass("invert");
   });
  $("#p2").on("isOnElement.changeMenuColor", function(){
       console.log("im on page 2");
      //lets invert color
      $(".menu").addClass("invert");
   });
  $("#p3").on("isOnElement.changeMenuColor", function(){
       console.log("im on page 3");
       //lets invert color
      $(".menu").addClass("invert");
   });
});

There are a bunch of ways to do this effect....if its involving scroll, you need javascript....waypoints.js is great for this..very simple

define a waypoint

$('you put the object that you want to trigger the css change here...when this object hits the top of the viewport').waypoint(function(){ $('this is the object your changing the css on').css("color", "red"); });

hope this helps

Adding a fixed postion to the menu could be enough, but that depends on your code. For changing the color, you will have to use jQuery. I was going to create a fiddle for you, but it seems the website is down at the moment. Just do a Google search for 'Change color jQuery scroll'. You should find enough examples with explantion on how to implement it.