There is a section, which has 11 article element tags. I want to observe the first and last article tag, and based on their visibility I want to hide the previous and next click.
Hide the Previous click: when the first element is visible.
Hide next click: when the last element is visible.
CSS flex-box arrangement is such that in the viewport at a time only 3 elements are visible.
i come up with some code:
const nextClick = document.querySelector(".next");
const previousClick = document.querySelector(".previous");
let observer = new IntersectionObserver(function(entries) {
entries.forEach(entry => {
console.log(entry);
if (entries[0].isIntersecting) {
previousClick.classList.toggle("disableClick");
}
if (entries[entries.length-1].isIntersecting) {
nextClick.classList.toggle("disableClick");
}
});
})
var allArticleInSection = document.querySelectorAll("section.slider article");
allArticleInSection.forEach( section => {
observer.observe(section);
});
My understanding is these lines are not written correctly as they are not part of a nodelist:
Hi @codeispoetry, you can get a reference to the actual DOM element via the entry.target property, and then check for the index in the articles in the node list like so:
for (let i = 0 ; i < allSectionArticleNumber; i++) {
nodeHolidayClass[i].classList.remove("holidayclass");
}
allSectionArticleNumber = 3 in current situation. would it be possible to be certain that this should run only when nodeHolidayClass[i] actually exists? It is possible in certain situations that
nodeHolidayClass[0]
nodeHolidayClass[1] → This may not be existing in certain situation.
nodeHolidayClass[2] → This may not be existing in certain situation.
we have to check true or false.
I can use if statement, but is there any condensed way to shorten it?
Yes you can check if the class list contains() that class, but this doesn’t seem necessary here… if it doesn’t, remove()ing that class simply does nothing.
Ah okay, I thought you meant to check if the class exists on the element… if the element itself may not exist, there’s no way around checking for that beforehand.
Are you sure this will always work though? For instance, if the second section doesn’t have an associated “holiday” element but the third one does, then the mapping will get mixed up…