<div id="parent">
<div id="id"></div>
</div>
const options = { threshold: 1.0 };
const callback = (entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
getAPI();
console.log('화면에서 노출됨');
} else {
console.log('화면에서 제외됨');
}
});
}
const observer = new IntersectionObserver(callback, options);
observer.observe(
document.getElementById('id')
);
let isLast = false;
function getAPI(){
if(isLast) return;
const $parent = document.getElementById("parent");
const $child = document.createElement('div');
$child.classList.add('item');
document.getElementById('id').setAttribute('id', '');
for (let i =0; i<10; i++) {
const $el = $child.cloneNode()
if(Array.from($parent.children).length > 45) {
isLast = true;
break;
}
if(i===9){
$el.setAttribute('id', 'id');
observer.observe($el);
}
$el.innerHTML = Array.from($parent.children).length;
$parent.append($el);
};
}
Intersection Observer API는 관측하는 Target Element가 viewPort에 교차하는 순간을 감지하는 API입니다.
그러니까 Target으로 지정한 Element가 지금 화면에 보이는지 여부를 판단할 수 있습니다.
// Observer 옵션
const options = {
root: document.querySelector('#scrollArea'),
rootMargin: '0px',
threshold: 1.0
}
// 타겟 Viewport에서의 변화 감지 -> 화면에 보이거나, 사라질 때 실행될 함수
const callback = (entries, observer) => {
entries.forEach(entry => {
// target element:
// entry.boundingClientRect
// entry.intersectionRatio
// entry.intersectionRect
// entry.isIntersecting
// entry.rootBounds
// entry.target
// entry.time
});
};
// Observer 선언
const observer = new IntersectionObserver(callback, options);
// 타겟 요소 관측 시작
observer.observe(TargetElement);
// 타겟 요소 관측 중단
observer.unobserve(TargetElement);
// 모든 요소 관측 중단
observer.disconnect();
// 관측 중인 모든 요소를 배열 형태로 반환
observer.takeRecords();
https://developer.mozilla.org/ko/docs/Web/API/Intersection_Observer_API