Last active
December 15, 2015 18:38
-
-
Save jnns/5304838 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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