Skip to content

Instantly share code, notes, and snippets.

@WebMaestroFr
Created June 18, 2014 10:09
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 WebMaestroFr/38d483732ef8822bea99 to your computer and use it in GitHub Desktop.
Save WebMaestroFr/38d483732ef8822bea99 to your computer and use it in GitHub Desktop.
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