fkhadra / react-on-screen

Check if a react component in the viewport
https://fkhadra.github.io/react-on-screen/
MIT License
405 stars 50 forks source link

addEventListener on element other than window #27

Open Yehudamoskowitz opened 6 years ago

Yehudamoskowitz commented 6 years ago

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?

oskarleonard commented 6 years ago

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);
  }
sjaugmented commented 4 years ago

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