sushibrain
sushibrain

Reputation: 2790

Changing a CSS property of an element when that element scrolls past a line

I'm working on a website, within this website, there is a scroll icon that has a fixed position and thus scrolls with the user. Because of the duotone design of the website, I'd like this icon to change color when it goes from a light to a dark background. Small example: enter image description here

As you can see, the scroll text is now white, on a dark background. However, when it scrolls over to the white side, I'd like the scroll text to become dark.

What I did try to do is use the waypoints library to make every light section a waypoint and then change colors like this:

$('.light').waypoint(function(direction) {
    $(".scroll").find('span').css('color', '#000');
});

However, this would only activate when the user reaches the bottom of the .light element.

Is there a way to do this in a smoother fashion? Thanks.


edit Like asked in the comments, here's a codepen: https://codepen.io/anon/pen/ZyYBKM

Upvotes: 0

Views: 92

Answers (1)

JiFus
JiFus

Reputation: 968

Of course this is possible. To achieve this effect you will have to set an offset. In this case the offset would be 100%.

The updated code:

$('.light').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    }
  },
  offset: '100%'
});
$('.dark').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    }
  },
  offset: '100%'
});

Link to a codepen

Upvotes: 2

Related Questions