Skip to content

Instantly share code, notes, and snippets.

@pelish8
Last active August 29, 2015 13:56
Show Gist options
  • Save pelish8/9023893 to your computer and use it in GitHub Desktop.
Save pelish8/9023893 to your computer and use it in GitHub Desktop.
/*!
* jQuery.scrollToElement
* Licensed under MIT
* https://gist.github.com/pelish8/9023893
* @author Aleksandar Stevic
* @version 0.0.1
*/
; (function ($) {
$.fn.scrollToElement = function (el, options) {
var $el = jQuery(el),
parentTop = this.scrollTop(),
parentBottom = parentTop + this.height(),
elTop = $el.position().top,
elBottom = elTop + $el.height() + parentTop,
offset;
if (elBottom >= parentBottom) {
// go down
offset = parentTop + elBottom - parentBottom;
if (options) {
this.animate({
scrollTop: offset
}, options);
} else {
this.scrollTop(offset);
}
} else if (elTop < 0) {
// go up
offset = parentTop + elTop;
if (options) {
this.animate({
scrollTop: offset
}, options);
} else {
this.scrollTop(offset);
}
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment