Created
October 19, 2021 03:12
-
-
Save bambooom/da5b85c9ffe647c516de9959acf2e886 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// modified from https://gist.github.com/hsablonniere/2581101 | |
function getParent(el) { | |
var parent = el.parentNode; | |
if (parent === document) { | |
return document; | |
} else if (parent.offsetHeight < parent.scrollHeight || parent.offsetWidth < parent.scrollWidth) { | |
return parent; | |
} else { | |
return getParent(parent); | |
} | |
} | |
// scrollIntoViewIfNeeded not supported in IE, Firefox | |
if (!Element.prototype.scrollIntoViewIfNeeded) { | |
Element.prototype.scrollIntoViewIfNeeded = function (centerIfNeeded) { | |
centerIfNeeded = arguments.length === 0 ? true : !!centerIfNeeded; | |
var parent = getParent(this), // not only with direct parent | |
parentComputedStyle = window.getComputedStyle(parent, null), | |
parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')), | |
parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')), | |
overTop = this.offsetTop - parent.offsetTop < parent.scrollTop, | |
overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight), | |
overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft, | |
overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth), | |
alignWithTop = overTop && !overBottom; | |
if ((overTop || overBottom) && centerIfNeeded) { | |
parent.scrollTop = this.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + this.clientHeight / 2; | |
} | |
if ((overLeft || overRight) && centerIfNeeded) { | |
parent.scrollLeft = this.offsetLeft - parent.offsetLeft - parent.clientWidth / 2 - parentBorderLeftWidth + this.clientWidth / 2; | |
} | |
if ((overTop || overBottom || overLeft || overRight) && !centerIfNeeded) { | |
this.scrollIntoView(alignWithTop); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment