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 callbackHow 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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
