Developers Diary

Affix a class on scroll

Featured Post Image - Affix a class on scroll

Bootstrap’s data-spy functionality was working, but then it started getting hung-up and not loading.  This site had the possibility of caching from 3 different sources (Bootstrap CDN, hosting caching, and Cloudflare CDN) and I think it was not allowing resources to load correctly.  I eliminated the data-spy option, and went straight to executing with just JavaScript, which seemed to eliminate the erratic behavior.

//caches a jQuery object containing the header element
var bumperredcon = $(".noBumper");
//the data-spy functionality for bootstrap stopped working, prob conflict with caching. Disable dataspy, rely only on this JS to add/remove the .affix class.
var bumperwhitepart = $(".noaffix");
$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 100) {
bumperredcon.removeClass('noBumper').addClass("navBumper");
bumperwhitepart.removeClass('noaffix').addClass("affix");
} else {
bumperredcon.removeClass("navBumper").addClass('noBumper');
bumperwhitepart.removeClass("affix").addClass('noaffix');
}
});

The bumperredcon and bumperwhitepart are just some variables I have to declare so the script can continue to look for the actual named classes to remove (and then add). So unlike CSS or other coding techniques, it’s not actually looking for #bumperredcon nor #bumperwhitepart, those do not exist in my DOM.  It’s like I had to create a “car” and that car looks around the DOM for the specified classes it is supposed to add and remove.  Additionally, I had to add “noaffix” as the default class so the car had something to look for to get to replacing.

This was a bit of a hard concept for me to understand.