Skip to content

Instantly share code, notes, and snippets.

@AMongeMoreno
Created January 15, 2015 11:13
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 AMongeMoreno/a24bb5019700438a5af5 to your computer and use it in GitHub Desktop.
Save AMongeMoreno/a24bb5019700438a5af5 to your computer and use it in GitHub Desktop.
jQuery plugin to set scroll followable items i.e. they follow the scroll but from one point to another they take fixed position.
$.fn.follow = function (from, to, offset, fixedOptions) {
var $this = this,
$window = $(window);
offset = offset || 0;
fixedOptions = fixedOptions || {};
from_y = from || 0;
to_y = to || Number.MAX_VALUE;
$window.scroll(function (e) {
if (isNaN(from)){
from_y = $(from).offset().top
}
if (isNaN(to)){
to_y = $(to).offset().top - parseInt($(to).css('margin-top')) - parseInt($(to).css('padding-top')) - $this.outerHeight() - offset;
}
if ($window.scrollTop() < from_y){
$this.css({
position: 'relative',
top: 0,
});
}else if ($window.scrollTop() >= from_y && $window.scrollTop() <= to_y) {
$this.css({
position: 'fixed',
top: offset,
});
$this.css(fixedOptions);
} else if ($window.scrollTop() > to_y){
$this.css({
position: 'relative',
top: to_y - from_y,
});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment