Tengo un sitio web con diferentes secciones. Estoy usando segment.io para rastrear diferentes acciones en la página. ¿Cómo puedo detectar si un usuario se ha desplazado hasta el final de un div? Intenté lo siguiente, pero parece activarse tan pronto como me desplazo por la página y no cuando llegué al final del div.
componentDidMount() { document.addEventListener('scroll', this.trackScrolling); } trackScrolling = () => { const wrappedElement = document.getElementById('header'); if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) { console.log('header bottom reached'); document.removeEventListener('scroll', this.trackScrolling); } };Una forma aún más sencilla de hacerlo es con scrollHeight , scrollTop y clientHeight .
Reste la altura desplazada de la altura desplazable total. Si esto es igual al área visible, ¡has llegado al fondo!
element.scrollHeight - element.scrollTop === element.clientHeight En reaccionar, simplemente agregue un oyente onScroll al elemento desplazable y use event.target en la devolución de llamada.
class Scrollable extends Component { handleScroll = (e) => { const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight; if (bottom) { ... } } render() { return ( <ScrollableElement onScroll={this.handleScroll}> <OverflowingContent /> </ScrollableElement> ); } } Encontré que esto es más intuitivo porque se trata del elemento desplazable en sí, no de la window , y sigue la forma normal de hacer las cosas en React (sin usar ID, ignorando los nodos DOM).
También puede manipular la ecuación para que se active más arriba en la página (contenido de carga diferida/desplazamiento infinito, por ejemplo).
puede usar el.getBoundingClientRect().bottom para verificar si se ha visto la parte inferior
isBottom(el) { return el.getBoundingClientRect().bottom <= window.innerHeight; } componentDidMount() { document.addEventListener('scroll', this.trackScrolling); } componentWillUnmount() { document.removeEventListener('scroll', this.trackScrolling); } trackScrolling = () => { const wrappedElement = document.getElementById('header'); if (this.isBottom(wrappedElement)) { console.log('header bottom reached'); document.removeEventListener('scroll', this.trackScrolling); } };Aquí hay una solución usando React Hooks y ES6:
import React, { useRef, useEffect } from 'react'; const MyListComponent = () => { const listInnerRef = useRef(); const onScroll = () => { if (listInnerRef.current) { const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current; if (scrollTop + clientHeight === scrollHeight) { // TO SOMETHING HERE console.log('Reached bottom') } } }; return ( <div className="list"> <div className="list-inner" onScroll={() => onScroll()} ref={listInnerRef}> {/* List items */} </div> </div> ); }; export default List;