Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply a "floating" effect on a sidebar
jQuery(document).ready(function ($) {
'use strict';
var content = $('#content'),
sidebar = $('#sidebar', content),
position = 0;
content.css({
position: 'relative',
minHeight: sidebar.height()
});
sidebar.css({
position: 'absolute',
top: 0,
right: 0
});
$(window).scroll(function () {
var scroll = $(window).scrollTop(),
direction = scroll - position, // down > 0, up < 0
min = content.offset().top,
max = min + content.height() - $(window).height(),
top = sidebar.offset().top,
bottom = top + sidebar.height() - $(window).height();
position = scroll;
if (scroll < min) {
sidebar.css({ top: 0 });
} else if (scroll > max) {
sidebar.css({ top: content.height() - sidebar.height() });
} else if (direction > 0 && scroll > bottom) {
sidebar.css({ top: scroll - min - sidebar.height() + $(window).height() });
} else if (direction < 0 && scroll < top) {
sidebar.css({ top: scroll - min });
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.