Skip to content

Instantly share code, notes, and snippets.

@Zirak
Created September 12, 2014 17:14
Show Gist options
  • Save Zirak/2effbe232f3c7d961eca to your computer and use it in GitHub Desktop.
Save Zirak/2effbe232f3c7d961eca to your computer and use it in GitHub Desktop.
scrollIntoViewIfNeeded
// centering doesn't work I don't care fuck you sideways
Element.prototype.scrollIntoViewIfNeeded = function (centerIfNeeded) {
var box = this.getBoundingClientRect(),
parentNode = this.parentNode,
parent = parentNode.getBoundingClientRect();
var above = box.top < parent.top,
below = box.bottom > parent.bottom,
toRight = box.right > parent.right,
toLeft = box.left < parent.left;
// still in the box, no need to worry.
if (!(above || below || toRight || toLeft)) {
return;
}
var alignWithBottom = below && !above;
if (!centerIfNeeded) {
return this.scrollIntoView(alignWithBottom);
}
// centering is...tricky. You need to take a lot of things into
//consideration. Fortunately, this is more of a hack than anything in
//the first place, so I cut a lot of slack.
if (above || below) {
parentNode.scrollTop = box.top + parent.height / 2;
}
if (toLeft || toRight) {
parentNode.scrollLeft = box.left + parent.width / 2;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment