Skip to content

Instantly share code, notes, and snippets.

@aravindet
Last active December 30, 2015 08:49
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 aravindet/7804922 to your computer and use it in GitHub Desktop.
Save aravindet/7804922 to your computer and use it in GitHub Desktop.
Ensure that chosen elements remain visible when the page scrolls. Elements appear to dock and undock from the window edges in a natural way.
jQuery.fn.fixInView = function() {
var lastTop = 0,
columns = this,
$ = jQuery;
function reposition() {
var top = $(window).scrollTop(),
height = $(window).height(),
up = lastTop > top;
if(lastTop == top) return;
columns.each(function () {
var column = $(this),
cHeight = column.outerHeight(),
cTop = column.offset().top,
small = cHeight < height;
if(
(!small && up || small && !up) &&
column.data('fixedInView') == 'bottom'
) {
column.data('fixedInView', 'none');
column.css({
position: 'absolute',
top: lastTop + height - cHeight,
bottom: 'auto'
});
}
else if(
(!small && !up || small && up) &&
column.data('fixedInView') == 'top'
) {
column.data('fixedInView', 'none');
column.css({
position: 'absolute',
top: lastTop,
bottom: 'auto'
});
}
else if(
(!small && up && cTop > top) ||
(small && !up && cTop < top)
) {
column.data('fixedInView', 'top');
column.css({
position: 'fixed',
top: 0,
bottom: 'auto'
});
}
else if(
(!small && !up && cTop + cHeight < top + height) ||
(small && up && cTop + cHeight > top + height)
) {
column.data('fixedInView', 'bottom');
column.css({
position: 'fixed',
top: 'auto',
bottom: 0
});
};
});
lastTop = top;
}
$(window).scroll(reposition);
$(window).resize(function() {
lastTop = $(window).scrollTop() + 1;
reposition();
lastTop = $(window).scrollTop() - 1;
reposition();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment