I have horizontally scrollable div with list (li) elements in it. How can I check if particular list element is scrolled into horizontal view by at least 50%?
I have horizontally scrollable div with list (li) elements in it. How can I check if particular list element is scrolled into horizontal view by at least 50%?
You can make use of offsetLeft, clientWidth and scrollLeft of the parent and the child you want to watch.
elementToMonitor.parentNode.addEventListener("scroll", function(event) {
const visible = this.scrollLeft + this.clientWidth,
isStartVisible = visible >= elementToMonitor.offsetLeft + (elementToMonitor.clientWidth / 2),
isEndVisible = visible <= elementToMonitor.offsetLeft + this.clientWidth + (elementToMonitor.clientWidth / 2);
// if both are true, item is visible relative to scroll position
// this does not mean, it is visible in the viewport
if (isStartVisible && isEndVisible) {
elementToMonitor.setAttribute("style", `color: white; background-color: purple; border: 5px solid green; border-radius: 1em;`);
} else {
elementToMonitor.removeAttribute("style");
}
});
div {
overflow: auto;
white-space: nowrap;
}
span {
display: inline-block;
border: 1px solid black;
margin-right: 0.5em;
}
.spacer {
width: 100vw;
}
.spacer::before {
content: "Placeholder";
}
<div>
<span class="spacer"></span>
<span id="elementToMonitor">Make me purple!</span>
<span class="spacer"></span>
</div>