Last active
April 9, 2016 11:21
-
-
Save akmur/fec7fff9ed952b4e51aa822c933fdeab to your computer and use it in GitHub Desktop.
Sticky Header script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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