0

I'm trying to add 2 classes to a div, the first needs adding at the point WHEN scrolltop equals a certain amount, the second is added IF scrolltop is greater than a certain amount.

Here is my jQuery code:

var Scroll = $(window).scrollTop();
var ScrollFXfullHeight = $('.header-wrapper').height(); 

    if (Scroll == ScrollFXfullHeight) {
        $("#navigation, .hidden_menu_link_container").addClass("fixed");
    } else if (Scroll > ScrollFXfullHeight) {
        $("#navigation, .hidden_menu_link_container, .stop_the_jump").addClass("thinner");  
    }

The above solution obviously uses 2 if statements, the issue here is that the page must exactly equal ScrollFXfullHeight for the first class to be added, however, if you just quickly scroll past it then the event is not triggered.

Is there a way of saying "WHEN Scroll == ScrollFXFullHeight add class" so it does it even when it is scrolled past?

Sam Skirrow
  • 3,647
  • 15
  • 54
  • 101
  • Not really, no. The scroll only updates as quick as the browsers'UI thread lets it, hence why there are gaps in the scrollTop value. Surely the logic is flawed here anyway, as once the `Scroll == ScrollFxFullHeight` is triggered the `Scroll > ScrollFxFullHeight` would be true anyway? – Rory McCrossan Jan 14 '15 at 13:29

1 Answers1

1

Check if Scroll is greater than or equal to ScrollFXfullHeight, then check if your element already has the class fixed. If not, add it:

if (Scroll >= ScrollFXfullHeight) {
    if(!$("#navigation, .hidden_menu_link_container").hasClass('fixed')) { 
        $("#navigation, .hidden_menu_link_container").addClass("fixed");   
    } 
    $("#navigation, .hidden_menu_link_container, .stop_the_jump").addClass("thinner");
}

This way, even if the user scrolls past that exact point, the class will still be added, but only added once. I feel you should probably also check if the thinner class has already been added as well, but that's your call

Brett Gregson
  • 5,867
  • 3
  • 42
  • 60