Check if element scrolled into horizontal view by 50%

Viewed 34

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%?

1 Answers

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>

Related