Skip to content

Instantly share code, notes, and snippets.

@jnns
Last active December 15, 2015 18:38
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 jnns/5304838 to your computer and use it in GitHub Desktop.
Save jnns/5304838 to your computer and use it in GitHub Desktop.
/*
Fixed positioning an element for as long as it's in the boundaries of its parent element.
Have an element stay in a particular position of the viewport,
but only inside a container element.
This is a function to extend jQuery. If you specify a parent element, the targeted
element will have `position: fixed` for as long as it is inside the parent's boundaries;
from then on, it switches over to `position: absolute`.
*/
$.fn.followTo = function ( parent ) {
var $this = this,
original_top = $this.offset().top;
bottom_of_parent = parent.offset().top + parent.height();
bottom_of_this = original_top + $this.height();
$(window).scroll(function(e){
if (($(window).scrollTop() + bottom_of_this) > bottom_of_parent) {
$this.css({
position: 'absolute',
top: bottom_of_parent - $this.height() + "px"
});
} else {
$this.css({
position: 'fixed',
top: original_top + "px"
});
}
});
};
$(document).ready(function () {
$("div#fixed").fixedIn($("div#fixed").parent("div"));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment