Tengo una matriz con elementos que quiero presentar en un div con una altura de 150 px con un desplazamiento infinito.
He buscado en Intersection Observer, pero no puedo encontrar nada que pueda usar, ya que mi caso de uso es muy simple. Los elementos que quiero introducir en un pergamino infinito se ven así:
const data = ["honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota"]
<Container> <ul> {data.map((d, index) => ( <li key={`${index}`}> <div> <span>some text</span> <span>some text</span> <span>some text</span> </div> </li> ))} </ul> </Container>
Me gustaría tener el pergamino infinito dentro del contenedor div.
(function () { const containerEl = document.querySelector('container'); const itemsEl = document.querySelector('.items'); const loaderEl = document.querySelector('.loader'); const items = ["honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab", "toyota","honda", "vw","opel", "saab"]; const getItems = (page,limit) => { const data = {'data':items.slice((page - 1)*limit,page*limit), 'total':items.length} return data; } const showItems = (items) => { items.forEach(item => { const itemEl = document.createElement('item'); itemEl.classList.add('item'); itemEl.innerHTML = `${item} `; itemsEl.appendChild(itemEl); }); }; const hasMore = (page, limit, total) => { const startIndex = (page - 1) * limit + 1; return total === 0 || startIndex < total; }; const loadItem = (page, limit) => { if (hasMore(page, limit, total)) { const fetched=getItems(page, limit); showItems(fetched['data']); total = fetched['total']; } }; let currentPage = 1; let limit = 6; let total = 0; containerEl.addEventListener('scroll', () => { const { scrollTop, scrollHeight, clientHeight } = containerEl; if (scrollTop + clientHeight >= scrollHeight - 5 && hasMore(currentPage, limit, total)) { currentPage++; loadItem(currentPage, limit); } }, { passive: true }); loadItem(currentPage, limit); })();
* { margin: 0; padding: 0; box-sizing: border-box; } container { margin: 0 auto; display: flex; flex-direction: column; justify-content: center; align-items: center; height:150px; background:#999999; overflow:scroll; } .items { display: flex; flex-direction: column; justify-content: center; } .item { position: relative; font-size: 20px; line-height: 1.7em; }
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Infinite Scroll</title> </head> <body> <Container> <div class="items"></div> </Container> </body> </html>
Usando este buen tutorial: JavaScript Infinite Scroll