Skip to content

Instantly share code, notes, and snippets.

@Munter
Created November 7, 2014 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Munter/1027cc8923ae3e17379e to your computer and use it in GitHub Desktop.
Save Munter/1027cc8923ae3e17379e to your computer and use it in GitHub Desktop.
A function to find the minimum scrollTop offset to scroll the given element into view of its scrolling ancestor.
define(function (require) {
function findScrollParent(el) {
return $(el).scrollParent()[0]; // FIXME: scrollParent adds a jquery UI dependency
}
return function (element, margin) {
if (!element instanceof HTMLElement) {
throw new Error('scrollToMin: First argument must be a DOM node');
}
margin = margin || 0;
if (element) {
var child = element;
var parent = findScrollParent(element);
if (parent) {
var height = parent.offsetHeight;
var min = parent.scrollTop;
var max = min + height;
var diff = 0;
var top = child.offsetTop;
var bottom = top + child.offsetHeight;
var bigger = (parent.scrollHeight - margin) < child.offsetHeight;
if (bottom > max) {
// child is smaller than the parent and below the viewport
diff = bottom - max;
}
if (bigger || top < min) {
// child is above the viewport
// If the child is bigger than the viewport, always align to top
diff = top - min;
}
if (diff !== 0) {
// Only add margins if there is a reason to scroll
if (diff < 0) {
diff -= margin;
} else {
diff += margin;
}
}
return parent.scrollTop + diff;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment