Skip to content

Instantly share code, notes, and snippets.

@hashchange
Created August 17, 2015 14:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hashchange/c368ce9c642c1a70edda to your computer and use it in GitHub Desktop.
Save hashchange/c368ce9c642c1a70edda to your computer and use it in GitHub Desktop.
Returns the scroll target position for scrolling to the top of an element.
/**
* Returns the scroll target position for scrolling to the top of an element.
*
* Pass the result to a scrollTo method:
*
* - $scrollContainer.scrollTop( result ) for instant scrolling
* - $scrollContainer.scrollTo( result ) for animated scrolling with jQuery.scrollable
*
* @param {jQuery} $target the target element
* @param {jQuery} $scrollContainer either $(window), or a scrollable HTML element
* @param {number} [offset=0] additional distance, inserted between the container and the top of the target
* @returns {number}
*/
function getScrollTargetPosition ( $target, $scrollContainer, offset ) {
var containerBorderTopWidth,
containerTop = 0,
target = $target[0],
scrollContainer = $scrollContainer[0];
if ( ! $.isWindow( scrollContainer ) ) {
// The scroll container is an HTML element, not a window. Get its position, relative to the window.
//
// - We need to exclude the border of the container element because it doesn't scroll. (By contrast,
// padding does scroll.)
// - We fetch the top border width with clientTop if available (should be supported universally, but we'd
// better be safe).
containerBorderTopWidth = scrollContainer.clientTop;
if ( containerBorderTopWidth === undefined ) containerBorderTopWidth = parseFloat( $scrollContainer.css( "borderTopWidth" ) );
containerTop = scrollContainer.getBoundingClientRect().top + containerBorderTopWidth;
}
// Get the targeted scroll position, based on the top of the target element.
return $scrollContainer.scrollTop() + target.getBoundingClientRect().top - containerTop - ( offset || 0 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment