How do I add a class to the body using jQuery, scrollTop, and toggleClass

5k views Asked by At

I have a question concerning jQuery's scrollTop functionality, and it's ability to toggle a class based on the amount of vertical scroll.

What I am trying to accomplish is on any page with a "section.banner" class, that after you scroll past the banner a class is applied to the body tag. This will allow me to change the fill colors of several SVGs that are in the site's header, as well as a fixed positioned side nav that is for pagination.

I am terrible at javascript, and have been stuck searching and trying to get this for hours. any help will be greatly appreciated. Here's the code that I'm working with now (CodeKit is telling me it is wrong, which I am not surprised). The value of 200 is just a placeholder and will be calculated by the height of a fluid image. Full disclosure, I have no idea if the brackets and parenthesis are correct.

    // Header/Fixed Pagination Banner Scroll Recoloriing (toggle class)
    // Check If '.banner' Exists
    if( $('section.banner').length > 0) {

        $('body').scrollTop(function)() 
        {
            if $(window).scrollTop >= 200 {
                $('body').toggleClass('downtown');
                return false;
            }
        }
    }
1

There are 1 answers

7
Mathieu Labrie Parent On BEST ANSWER

Try something like this :

if( $('section.banner').length > 0) {

    $(window).scroll(function() {
    {

        if ($(window).scrollTop() >= $('section.banner').scrollTop()) {
            $('body').toggleClass('downtown');
            return false;
        }
    });
}

UPDATE

There was little mistake in my code : http://jsfiddle.net/t2yp15hq/

var top = $('section.banner').position().top;

if($('section.banner').length > 0) {

    $(window).scroll(function() {

        if ($(this).scrollTop() >= top) {
            $('body').addClass('downtown');

        }
        else
        {
            $('body').removeClass('downtown');
        }
    });
}

It does not work with toogleClass, the background is flashing.

UPDATE

http://codepen.io/anon/pen/wBWzXy

The solution is to recalculate the top when the window is resized :

$(window).resize(function(){
  top = $('section.story-intro').offset().top - 90;
});