[JS]자바스크립트 스크롤이벤트 - 페이드인

정훈·2022년 6월 1일
0

화면을 스크롤하면 요소들이 스르륵 나타나는 기능을 만들어 보자.

필요한것

  • 현재 화면의 높이
  • 대상 요소의 절대좌표

이벤트 대상의 절대좌표(px)가 현재 화면(px)에 진입하면 이벤트를 작동하는 방식이다.

기본코드

//html
<div class="box active">1번 박스</div>
<div class="box">2번 박스</div>
<div class="box">3번 박스</div>
<div class="box">4번 박스</div>

//css는 자유롭게..

우선 현재 화면의 윈도우사이즈와 요소의 절대좌표를 구해보자

  • getBoundingClientRect() : 요소가 기준점(.top)으로부터 얼마나 떨어져있는지 px로 알려줌
let windowHeight = window.innerHeight;
let elementLocation = element.getBoundingClientRect().top;

그리고 이벤트css를 적용할 함수를 만들어 보자.

items = document.querySelectorAll(".box");

function scrollEvent(){

  let windowHeight = window.innerHeight;
  

  items.foreach((item) => {
    let itemLocation = item.getBoundingClientRect().top;
    if(windowHeight > itemLocation){
    item.classList.add('active');
    }
  })
]

window.addEventListener("scroll", scrollEvent);

윈도우 사이즈는 고정이고, 요소까지의 거리는 스크롤을하면 점점 작아진다.

그래서 해당 요소가 윈도우사이즈 위치까지 오면 이벤트를 발생시키는 원리이다.

윈도우사이즈 이전or이후 적용하려면 상황에 맞게 기준값을 조정해주자
( ex_if(windowHeight > itemLocation + 300) )

결과화면

끝.

profile
꾸준히!

0개의 댓글