Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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