Skip to content

Instantly share code, notes, and snippets.

@matlc
Last active February 10, 2016 23:16
Show Gist options
  • Save matlc/2f222f2f47f7d82810bd to your computer and use it in GitHub Desktop.
Save matlc/2f222f2f47f7d82810bd to your computer and use it in GitHub Desktop.
A simple sticky-nav implementation
//http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.bottom > 0
);
}
window.onscroll = function(){
var stickynav = document.getElementById("js-sticky-nav-bar");
var stickyPastElement = document.getElementsById("elementToBeStickyAfter");
var visible = isElementInViewport(stickyPastElement);
if (!visible) {
stickynav.classList.add("stuck"); //.stuck class has position:fixed, top:0, etc.
} else {
stickynav.classList.remove("stuck");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment