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);


Resize the width of a text box to fit its content automatically
Scroll to an element smoothly