Skip to content

Instantly share code, notes, and snippets.

@akmur
Last active April 9, 2016 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akmur/fec7fff9ed952b4e51aa822c933fdeab to your computer and use it in GitHub Desktop.
Save akmur/fec7fff9ed952b4e51aa822c933fdeab to your computer and use it in GitHub Desktop.
Sticky Header script
var App = (function () {
// Sticky Header
var stickyHeader = function (navElement) { // needs the ID of the element
this.nav = document.getElementById(navElement);
this.siteBody = document.getElementsByTagName("body")[0];
this.stuck = false;
this.stickPoint = this.getDistance();
};
stickyHeader.prototype.getDistance = function() {
var topDist = this.nav.offsetTop;
return topDist;
}
stickyHeader.prototype.checkSticky = function() {
var distance = this.getDistance() - window.pageYOffset + 104;
var offset = window.pageYOffset;
var className = 'headerIsSticky';
var thisBody = this.siteBody;
if ( (distance <= 0) && !this.stuck) {
if (thisBody.classList) {
thisBody.classList.add(className);
} else {
thisBody.className += ' ' + className;
}
this.stuck = true;
} else if (this.stuck && (offset <= this.stickPoint)){
if (thisBody.classList) {
thisBody.classList.remove(className);
} else {
thisBody.className = thisBody.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');;
}
this.stuck = false;
}
}
// End stickyHeader
//exporting public functions
return {
stickyHeader: stickyHeader
};
})();
(function($) {
jQuery(document).ready(function($) {
var headerSticky = new App.stickyHeader('header'); // passing the ID of the element
window.onscroll = function() {
headerSticky.checkSticky();
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment