Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Created September 2, 2013 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhkeller/6413924 to your computer and use it in GitHub Desktop.
Save mhkeller/6413924 to your computer and use it in GitHub Desktop.
Browser sniffer for `position: sticky;`
function stickyTitles(stickies) {
this.load = function () {
stickies.each(function () {
var thisSticky = $(this).wrap('<div class="sticky-header-bump-wrap" />');
thisSticky.parent().height(thisSticky.outerHeight());
$.data(thisSticky[0], 'pos', thisSticky.offset().top);
});
}
this.scroll = function () {
stickies.each(function (i) {
var thisSticky = $(this),
nextSticky = stickies.eq(i + 1),
prevSticky = stickies.eq(i - 1),
pos = $.data(thisSticky[0], 'pos');
if (pos <= $(window).scrollTop()) {
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && thisSticky.offset().top >= $.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", $.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && $(window).scrollTop() <= $.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
}
}
// If it doesn't support `position: sticky;` do the js scroll method
if (!window.getComputedStyle(document.querySelector('.sticky-test')).position.match(/sticky/)) {
stickyBumpySections();
}else{
$('.sticky-section-hed').css({
'position': 'sticky',
'position': '-webkit-sticky',
'position': '-moz-sticky',
'position': '-o-sticky',
'position': '-ms-sticky',
'position': 'sticky',
'z-index': 1
});
};
function stickyBumpySections(){
var newStickies = new stickyTitles($(".sticky-section-hed"));
newStickies.load();
$(window).on("scroll", function () {
newStickies.scroll();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment