Skip to content

Instantly share code, notes, and snippets.

@aramk
Last active December 12, 2015 02:18
Show Gist options
  • Save aramk/4697855 to your computer and use it in GitHub Desktop.
Save aramk/4697855 to your computer and use it in GitHub Desktop.
Floats an element on the top of the screen when we scroll the page beyond it. This is useful for page headers for instance. The "overlap" CSS class is added and you can style it how you like. Something with position: fixed, top:0, left: 0 works well.
(function ($) {
function getPositionInfo(elem) {
var pos = {};
pos.docViewTop = $(window).scrollTop();
pos.docViewBottom = pos.docViewTop + $(window).height();
pos.elemTop = $(elem).offset().top;
pos.elemBottom = pos.elemTop + $(elem).height();
return pos;
}
function isScrolledIntoView(elem) {
var pos = getPositionInfo(elem);
return ((pos.elemBottom <= pos.docViewBottom) && (pos.elemTop >= pos.docViewTop));
}
function isScrolledOutOfView(elem) {
var pos = getPositionInfo(elem);
return ((pos.elemBottom <= pos.docViewTop) || (pos.elemTop >= pos.docViewBottom));
}
function isAboveTop(elem) {
var pos = getPositionInfo(elem);
return ((pos.elemTop <= pos.docViewTop));
}
function floatOnTop(elem) {
var origTop = null;
$(document).scroll(function () {
var top = $(elem).offset().top;
if (origTop == null && isAboveTop(elem.get(0))) {
origTop = top;
elem.addClass('overlap');
if ($('#wpadminbar').length) {
elem.addClass('wpadminbar');
}
} else if (origTop != null && top < origTop) {
elem.removeClass('overlap');
elem.removeClass('wpadminbar');
origTop = null;
}
});
$(document).trigger('scroll');
}
$(function () {
// Float the phone number when we scroll it off screen
var number = $('#masthead .phone-number');
floatOnTop(number);
})
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment