Skip to content

Instantly share code, notes, and snippets.

@bpb54321
Created August 4, 2016 17:57
Show Gist options
  • Select an option

  • Save bpb54321/f09dfa8cdc0d3b43cd2b823226339418 to your computer and use it in GitHub Desktop.

Select an option

Save bpb54321/f09dfa8cdc0d3b43cd2b823226339418 to your computer and use it in GitHub Desktop.
/**
* Makes the filter bar sticky when it reaches the top of the screen by scrolling, and un-sticks it if you scroll above the screen.
* Also fills in the primary nav bar when the filter bar becomes sticky.
*/
function stickyFilterBar() {
window.filterBarIsFixed = false;
var filterSortBar = document.querySelector(".filter-sort-bar"); //Parent element
if (filterSortBar !== null) {
var topButtonBar = document.querySelector(".top-button-bar");
var topButtonBarHeight = jQuery(topButtonBar).height();
var primaryNavHeader = document.getElementById("header");
var primaryNavHeight = jQuery(primaryNavHeader).height();
var offsetTop = topButtonBar.offsetTop - primaryNavHeight; //The height at which the filter bar is just below the navbar
window.addEventListener("scroll", function () {
//console.log("ScrollY: " + window.scrollY);
//console.log("Offset: " + offsetTop);
var fixedClass = " fixed-to-top";
if ((window.scrollY >= offsetTop) && ( !window.filterBarIsFixed )) {
window.filterBarIsFixed = true;
filterSortBar.style.position = "fixed";
filterSortBar.style.zIndex = "2";
filterSortBar.style.top = primaryNavHeight + "px";
//When the bar becomes fixed, need to add to the top margin of next sibling so that it doesn't slide under
//the fixed filter bar.
filterSortBar.nextElementSibling.style.marginTop = topButtonBarHeight + "px";
//Fill in the background color of the primary nav
primaryNavHeader.style.backgroundColor = "#332b2a";
}
if ((window.scrollY < offsetTop) && ( window.filterBarIsFixed )) {
window.filterBarIsFixed = false;
filterSortBar.style.position = "static";
filterSortBar.style.zIndex = "initial";
filterSortBar.nextElementSibling.style.marginTop = "0px";
//Change back to transparent the background color of the primary nav
primaryNavHeader.style.backgroundColor = "transparent";
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment