- IntersectionObserver
- class를 이용한 ProjectView
- 후기
IntersectionObserver란?
사용자 화면에 지금 보이는 요소인지 아닌지를 구별하는 기능 제공
const io = new IntersectionObserver(callback, options) //관찰자 초기화
io.observer(element) // 관찰자 대상(요소) 등록
관찰할 대상(target)이 등록되거나 가시성(보이는지 보이지 않는지)에 변화가 생기면 콜백을 실행합니다.
콜백은 2개의 인수(entries, observer)를 가집니다.
// IntersectionObserver
const io = new IntersectionObserver((entries, observer) => {
//눈에 보이기 시작한 객체 isIntersecting : true;
//완전히 눈에서 사라진 객체 isIntersecting : false;
for (let i = 0; i < entries.length; i++ ) {
if (entries[i].isIntersecting) {};
}
}
observerElems.forEach((item, i) => {
io.observe(item);
});
observerElems을 io.observe(item)을 통해 관찰 대상으로 지정하고 entries[i].isIntersecting 이 true일때 즉 observerElems이 눈에 보이기 시작 할 때 panel 이미지가 가까이 오게 코딩 하였습니다.
class ProjectView {
constructor() {
this.bodyElem = document.createElement('div');
this.bodyElem.classList.add('cover-panel');
document.body.appendChild(this.bodyElem);
this.bodyElem.addEventListener('click', (e) => {
if(e.target.classList.contains('back-btn')){
this.hide();
}
});
}
show(data) {
document.body.classList.add('scroll-rock');
this.bodyElem.style.backgroundColor = `${data.color}`
this.bodyElem.innerHTML = `<section class="project-view">
<button class="back-btn"><span></span></button>
<header class="project-view-header">
<div class="width-setter">
<h1 class="project-view-title">${data.title}</h1>
</div>
</header>
<div class="project-view-content width-setter">
<figure class="a11y-hidden-bg project-view-image" style="background-image: url('${data.image}');">
<img class="a11y-hidden" src="${data.image}" alt="${data.title}">
</figure>
<div class="project-view-desc width-setter">
${data.description}
</div>
</div>
</section>`;
const timeId = setTimeout(() => {
this.bodyElem.classList.add('active');
clearTimeout(timeId);
}, 10);
}
hide() {
this.bodyElem.classList.add('close');
const timeId = setTimeout(() => {
this.bodyElem.classList.remove('active', 'close');
document.body.classList.remove('scroll-rock');
clearTimeout(timeId);
}, 1000);
}
}
new ProjectView()를 이용하여 view button을 클릭시 constructor을 통해 body의 젤 마지막 자식으로 class가 cover-panel인 div element를 만들고 show()함수 실행시 project-view로 만들었던 html을 찍어 내도록 설계 하였습니다.
반대로 hide()함수 실행시 body에 보여줬던 project-view가 사라지도록 코딩 하였습니다.
setTimeout없이 this.bodyElem.classList.add('active');를 추가하니 css transition효과가 나타나지 않았습니다. 그래서 setTimeout함수를 통해 지연시킨후 classList에 active, remove를 추가 해 주었습니다.
이번 interactive 강의를 통해 처음 보았던 IntersectionObserver에 대해 깊게 이해 할 수 있었습니다. 나중에 IntersectionObserver를 이용하여 여러 interactive한 페이지도 만들고 싶은 생각도 들었습니다! 이를 활용한다면 더욱 화려한 웹 페이지를 만들 수도..
class 문법에대해 한번 더 기초를 다지는 수업이 된 것 같습니다. js를 오랜만에 하게되어 까먹은 내용도 많은데 이번 클론 강의를 통해 한번 더 기초를 다지는 시간이 된 것 같습니다.
무엇보다도 먼저 저가 구현해보고 그 뒤 강의를 듣고하니 더 이해가 잘되고 나의 코드에 어떤 부분이 잘 되었는가 깨닫는 시간이 된 것 같아 보람찹니다 ㅎㅎ
IntersectionObserver를 배우고 나니 scroll이벤트를 통한 interactive web과 어떤 차이가 있는지 궁금하여 다음에 한번 살펴 볼 예정입니다!