비동기적인 요소의 인터섹션을 감지한다.
const boxes = document.querySelector(".box")
const observer = new IntersectionObserver((entries, observer) => {
console.log(entries)
entries.forEach(entry=>{
console.log(entry.target);
if(entry.isIntersecting){
entry.target.classList.add('active')
}else{
entry.target.classList.remove('active')
}
})
console.log(observer)
}, {
root:null,
rootMargin:0,
threshold: 1,
})
boxes.forEach(box => observer.observer(box))
예제
const sectionIds = ["#home","#about","#skills","#testimonials","#contack"];
const sections = sectionIds.map(document.querySelector);
const navITems = sectionIds.map(id => document.querySelector(`[data-link=${id}]`));
let selectedNavIndex = 0;
let selectedNavItem = navItem[0]
const selectedItem = (selected) => {
selectedNavItem.classList.remove('active');
selectedNavItem = selected;
selectedNavItem.classList.add('active');
}
const observerOptions = {
root:null,
rootMargin:'0px',
threshold:0.3
}
const observerCallback = (entries, observer)=> {
entries.forEach(entry => {
console.log(entry.target);
if(!entry.isIntersecting && entry.intersectionRation > 0){
const index = sectionIds.indexOf(`#{entry.target.id}`);
if(entry.boundingClientRect.y < 0){
selectedNavIndex = index + 1;
}else{
selectedNavIndex = index - 1;
}
}
})
}
const observer = new IntersectionObserber(observerCallback,observerOptions)
sections.forEach(observer.observer)
window.addEventLisnter('wheel', ()=>{
if(window.scrollY === 0){
selecteedNavIndex = 0;
}else if(Math.round(window.scrollY + window.innerHeight) >= document.body.clientHeight){
selectedNabInde = navItems.length - 1;
}
selectedItem(navItems[selectedNavIndex])
})