Scroll to an specific element inside any element
With this simple jquery function you can scroll to an element inside another scrollable area
Format : scrollableElement.scrollTo(innerElement)
Arugments : element, [{animation and speed}, [callback]]
Coffee code:
jQuery.fn.scrollTo = (el, options, callback)->
return unless el
$this = $ this
newScroll = $(el).offset().top - $this.offset().top + $this.scrollTop() - $this.height()/3
speed = Math.abs(newScroll - $this.scrollTop())/3
speed = 200 if speed < 200
options ||= {}
if options.animate
$this.animate({scrollTop: newScroll}, options.speed || speed, callback)
else
$this.scrollTop(newScroll)
callback() if callback
How it works:
Finds real position of element from scrollableElement and then calculate animation speed with the minimum of 200.
(compiled js)
jQuery.fn.scrollTo = function(el, options, callback) {
var $this, speed, newScroll;
if (!el) {
return;
}
$this = $(this);
newScroll = $(el).offset().top - $this.offset().top + $this.scrollTop() - $this.height() / 3;
speed = Math.abs(newScroll - $this.scrollTop()) / 3;
if (speed < 200) {
speed = 200;
}
options || (options = {});
if (options.animate) {
return $this.animate({
scrollTop: newScroll
}, options.speed || speed, callback);
} else {
$this.scrollTop(newScroll);
if (callback) {
return callback();
}
}
};Written by Kazem Keshavarz
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#