페이지 상단으로 이동(GSAP&ScrollTo)

김몬지·2021년 10월 8일
0

스타벅스 클론 코딩

목록 보기
22/23

페이지 상단으로 이동
GSAP과 ScrollTo 플러그인을 이용해 페이지 상단으로 이동하는 버튼을 작성한다.
기존의 JS를 활용해 약간의 코드만 추가하여 구현함.

코드

HTML

  <div id="to-top">
    <div class="material-icons">arrow_upward</div>
  </div>

CSS

#to-top {
  width: 42px;
  height: 42px;
  background-color: #333;
  color: #fff;
  border: 2px solid #fff;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 9;
}

JS

window.addEventListener('scroll', _.throttle(function () {
  console.log(window.scrollY);
  if (window.scrollY > 500) {
    // gsap.to(요소, 지속시간, 옵션);
    gsap.to(badgeEl, 0.6, {
    // 배지 숨기기
      opacity: 0,
      display: 'none'
    });
    gsap.to(toTopEl, 0.2, {
    // 투 탑 나타나기
      x: 0
    });
    
  } else {
    gsap.to(badgeEl, 0.6, {
    // 배지 보이기
      opacity: 1,
      display: 'block'
    });
    gsap.to(toTopEl, 0.2, {
      // 투 탑 숨기기
      x: 100
    });
  }
}, 300));
// _.throttle(함수, 시간)

toTopEl.addEventListener('click', function() {
  gsap.to(window, 0.7, {
    scrollTo: 0
  });
});
profile
프론트엔드 공부하는 사람

0개의 댓글