/html-dom /Intermediate
GitHub 4932★

Scroll an element to ensure it is visible in a scrollable container

The following functions scrolls the ele element if it's not visible in its scrollable container:

const scrollToBeVisible = function (ele, container) {
const eleTop = ele.offsetTop;
const eleBottom = eleTop + ele.clientHeight;

const containerTop = container.scrollTop;
const containerBottom = containerTop + container.clientHeight;

if (eleTop < containerTop) {
// Scroll to the top of container
container.scrollTop -= containerTop - eleTop;
} else if (eleBottom > containerBottom) {
// Scroll to the bottom of container
container.scrollTop += eleBottom - containerBottom;
}
};

See also

Follow me on and to get more useful contents.