Frontend/Javascript
[JS] 스크롤시 맨 위로 가기 버튼 만들기
밤토리아이티
2024. 3. 16. 23:49
728x90
안녕하세요. 현생을 사느라 포스팅이 조금 늦었습니다.
요즘 앱이나 웹에서 아래의 이미지와 같이 스크롤을 내리고나서 "위로가기" 버튼 많이 이용하시나요? (혹은 맨 아래로)
오늘은 간단하게 자바스크립트로 "위로가기" 버튼을 만들고자 아래의 코드를 공유합니다.
const element = document.documentElement;
// 스크롤 이벤트 리스너
window.addEventListener('scroll', () => {
const btnStyle = document.getElementById('btn-scroll-to-top').style;
// 스크롤을 했을때 100px을 초과하면 보이고 아니면 none 처리
btnStyle.display = element.scrollTop > 100 ? 'block' : 'none';
});
// 클릭 시 페이지 맨 위로 스크롤
const scrollToTop = () => {
const position = element.scrollTop;
if (position) {
window.requestAnimationFrame(() => {
window.scrollTo(0, position - position / 12);
scrollToTop();
});
}
}
const reactElement = (
<div>
<h1>It is a long established fact that a reader will be distracted</h1>
<h1>by the readable content of a page when looking at its layout.</h1>
<h1>The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,</h1>
... 이하 생략
<button onClick={scrollToTop} id="btn-scroll-to-top"><i class="fa fa-arrow-up"></i></button>
</div>
);
전체 코드
See the Pen code by 소윤정 (@xhcimfqy-the-animator) on CodePen.
본 글은 아래의 블로그를 참고했습니다
728x90