GSAP과 ScrollTo 플러그인을 이용해 페이지 상단으로 이동하는 버튼을 작성한다.
기존의 JS를 활용해 약간의 코드만 추가하여 구현함.
<div id="to-top">
<div class="material-icons">arrow_upward</div>
</div>
#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;
}
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
});
});