user3304303
user3304303

Reputation: 1043

How to add and remove a class on an element when Bootstraps Affix is affixed or not

On this dev page, as you scroll, the green "sticky" nav scrolls up and sticks to the top. When it sticks to the top, the class on ".sticky_cta" changes from "affix-top" to just "affix" (using bootstrap affix plugin).

I'd like to add a CSS class (called stickyoffset) to another element on the page (.belowbrandnav) when the sticky bar sticks, essentially. This class would bump everything down about 60px so text isn't hidden under the "sticky nav" when you click one of the industry icons to "jump" to the anchor.

This is code to make the sticky bar stick, and thus change the class to "affix".

// to make sub nav stick to top
$('.sticky_cta').each(function () {
    if ($(this).hasClass('affix')) {
        $('.belowbrandnav').addClass("stickyoffset");
    }
});

jQuery(function ($) {
    $(document).ready(function () {
        $('.sticky_cta').affix({
            offset: {
                top: $('.abovebrandnav').height() + 70
            }
        });
    });
});

I tried this code below and it works if I scroll the bar to the top and THEN refresh, so it's obviously not practical. I'd like it to do it automatically without a need to refresh.

// to make sub nav stick to top
//Sticky Bar Product Page
jQuery(function ($) {
    $(document).ready(function () {
        $('.sticky_cta').affix({
            offset: {
                top: $('.abovebrandnav').height() + 70
            }
        });
        $('.sticky_cta').each(function () {
            if ($(this).hasClass('affix')) {
                $('.belowbrandnav').addClass("stickyoffset");
            }
        });
    });
});

Am I on the right track, or approaching this wrong?

Upvotes: 1

Views: 2129

Answers (2)

Ted
Ted

Reputation: 14927

You'll want to tie into the events that bootstrap provides for affix.

Try this:

$(document).ready(function () {
    $('.sticky_cta').affix({
        offset: {top: $('.abovebrandnav').height() + 70}
    }).on('affix.bs.affix', function () {
        $('.belowbrandnav').addClass("stickyoffset");
    }).on('affix-top.bs.affix', function () {
        $('.belowbrandnav').removeClass("stickyoffset");
    });
});

Take a look at this bootply demo. I made it change the color of the 'Bootply' text in the navbar. Scroll, and you can see it adds the class when its scrolling with the pane, and removes it when it's not.

On a side note, I will say that bootstraps event naming is far less than intuitive for this plugin :P

Upvotes: 3

taxicala
taxicala

Reputation: 21759

You could bind an handler to the scroll event of the document:

$(document).on('scroll', function() {
    $('.sticky_cta').each(function(){
        if($(this).hasClass('affix')) {
            $('.belowbrandnav').addClass("stickyoffset");
        } 
    });
});

Upvotes: 1

Related Questions