I have this code where when i am scrolling down i am appending new elements
<div class="card-container">
<div class="card show">First card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
<div class="card">card</div>
</div>
JS
const cards = document.querySelectorAll('.card');
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
entry.target.classList.toggle('show', entry.isIntersecting);
})
})
const lastCardObserver = new IntersectionObserver(entries => {
const lastCard = entries[0];
if(!lastCard.isIntersecting) return
loadNewCards();
lastCardObserver.unobserve(lastCard.target);
lastCardObserver.observe(document.querySelector('.card:last-child'));
}, {rootMargin: '200px'})
const cardContainer = document.querySelector('.card-container');
function loadNewCards() {
for(let i = 0;i < 10;i++) {
const card = document.createElement('div');
card.textContent = 'new card';
card.classList.add('card');
card.classList.add(`card-${i}`);
observer.observe(card);
cardContainer.append(card);
}
}
cards.forEach(card => {
observer.observe(card);
})
lastCardObserver.observe(document.querySelector('.card:last-child'))
EVERYTHING WORKS FINE
but i need now when i am at the beggining at the element which is on the viewport, while i scroll up
to add new elements so to detect that i am scrolled to the first element in the viewport
How can i do that