Js Challenge14 - #8 Scroll animation

가짜 개발자·2023년 2월 14일
0

JS Challenge14

목록 보기
9/15

스크롤시 박스 애니메이션을 적용해 보았다.


✅ Goal

  • 스크롤 애니메이션 구현하기

✅ Keyword

getBoundingClientRect()
window.innerHeight

getBoundingClientRect() 메서드는 엘리먼트의 크기와 뷰포트에 상대적인 위치 정보를 제공하는 DOMRect 객체를 반환한다.

즉 브라우저 위에 하나의 엘리먼트 박스가 있다면 해당 엘리먼트의 좌표 값들을 얻을 수 있다. 고로 이 메서드를 활용해서 해당 엘리먼트의 top을 스크롤을 통해 위치를 파악할 수 있다.

window.innerHeigt는 현 브라우저의 높이 값을 알수있으며, 이 두개의 메서드를 통해 스크롤 애니메이션을 구현해보고자 한다.

https://developer.mozilla.org/ko/docs/Web/API/Element/getBoundingClientRect


🟢 scroll box 생성

반복문을 활용하여 BOXEX 길이만큼 박스를 생성하였다. 또 한 애니메이션 작업을 위해 생성 된 박스마다 box 클래스명을 넣었다.

const BOXES = 20;

for (let i = 0; i < BOXES; i++) {
  const contents = document.createElement("div");
  const h1 = document.createElement("h1");
  h1.innerText = `Scroll Box ${i}`;
  contents.classList.add("box");
  contents.appendChild(h1);
  container.appendChild(contents);
}

🟢 scroll animaiton

아래와 같이 getBoundingClientRect() 메서드를 활용하여 해당 엘리먼트 박스의 높이 좌표와 window.innerHeight를 활용하여 현 브라우저의 높이 값을 비교하여 해당 엘리먼트의 높이가 브라우저의 높이 보다 작을 경우 box의 클래스명을 조절하여 애니메이션을 구현하였다.

const boxes = document.querySelectorAll(".box");
window.addEventListener("scroll", scrollBoxes);
scrollBoxes();

function scrollBoxes() {
  const innerHeight = (window.innerHeight / 5) * 4;
  boxes.forEach((box) => {
    const boxTop = box.getBoundingClientRect().top;
    console.log("boxTop", boxTop, "innerHeight", innerHeight, boxTop < innerHeight);

    if (boxTop < innerHeight) {
      box.classList.add("show");
    } else {
      box.classList.remove("show");
    }
  });
}

🟥 조금은 고민했던 부분

innerHeigth와 해당 엘리먼트의 높이 값을 비교하면서 어떤 적절 위치에 스크롤 애니메이션을 적용 할지 고민을 했던 것 같다. 콘솔로그를 찍으면서 5로도 나눠 보고 10으로도 나눠보면서 값들을 계산하면서 진행하였고 아래와 같이 계산하여 스크롤 애니메이션을 진행 했을 때 부드러웠다.

 const innerHeight = (window.innerHeight / 5) * 4;


✅ 기능 시연 및 코드

개인 적으로 실제 데이터를 활용한 무한스크롤 기능을 연습 해볼 필요가 있다. 전에 무한스크롤을 구현하다 스크롤시 미세한 움직임에도 호출 해서 고생한 적이 있다... js 첼린지를 마무리하고 실제 데이터를 활용한 무한스크롤 기능을 구현 해봐야겠다!

🟢 Scroll animation


🟢 js code

// index.js
const container = document.getElementById("container");

const BOXES = 20;

for (let i = 0; i < BOXES; i++) {
  const contents = document.createElement("div");
  const h1 = document.createElement("h1");
  h1.innerText = `Scroll Box ${i}`;
  contents.classList.add("box");
  contents.appendChild(h1);
  container.appendChild(contents);
}

const boxes = document.querySelectorAll(".box");
window.addEventListener("scroll", scrollBoxes);
scrollBoxes();

function scrollBoxes() {
  const innerHeight = (window.innerHeight / 5) * 4;
  boxes.forEach((box) => {
    const boxTop = box.getBoundingClientRect().top;
    // console.log("boxTop", boxTop, "innerHeight", innerHeight, boxTop < innerHeight);

    if (boxTop < innerHeight) {
      box.classList.add("show");
    } else {
      box.classList.remove("show");
    }
  });
}

https://github.com/fake-dp/Js-Challenge14-Mini-Project/tree/main/ScrollBox
배포링크

profile
프론트 개발 일지

0개의 댓글