react-on-screen icon indicating copy to clipboard operation
react-on-screen copied to clipboard

addEventListener on element other than window

Open Yehudamoskowitz opened this issue 7 years ago • 2 comments

I have a parent element with overflow:auto. Therefore the scrolling event is triggered on this element and not on the window, so the child TrackVisibility components do not update on scroll. Can the scroll eventListener somehow be added to the parent element?

Yehudamoskowitz avatar May 22 '18 15:05 Yehudamoskowitz

Hmm, i guess it would be possible to extend the api with an eventListenerElement prop?

<TrackVisibility
  eventListenerElement={document.getElementById('MyElement')}
</TrackVisibility>
constructor(props) {
  this.eventListenerElement = props.eventListenerElement || window;
}
attachListener() {
  this.eventListenerElement.addEventListener("scroll", this.throttleCb);
  this.eventListenerElement.addEventListener("resize", this.throttleCb);
}

Or pass id to an element and do document.getElementById('ElementId') in TrackVisibility component

<TrackVisibility
  ElementId="ElementId"
</TrackVisibility>
  componentDidMount() {
    this.eventListenerElement = document.getElementById(this.props.ElementId);
    this.attachListener();
    setTimeout(this.isComponentVisible, 0);
  }

oskarleonard avatar Sep 17 '18 22:09 oskarleonard

Bump. Similar issue here. I've got my components in a sidebar with overflow-y: scroll and isVisible is always true.

sjaugmented avatar Sep 10 '20 00:09 sjaugmented