클릭하면 최상단으로 스크롤 이동하는 버튼 소스

2022. 7. 13. 15:49IT

클릭하면 최상단으로 스크롤 이동하는 버튼 소스

 

 

스크롤하면 버튼이 나타나고 클릭하면 최상단으로 이동

 

HTML

<div class="arrow-box"><span class="material-symbols-outlined">
Top</span></div>

 

CSS

body {height: 2000px; background: #eee;}

.arrow-box {
  position: fixed;
  width: 40px;
  height: 40px;
  background-color: brown;
  right: 20px;
  bottom: 40px;
  transition: all .3s ease;
  opacity: 0;
  pointer-events: none;
  color: #fff;
  text-align: center;
}

.arrow-box.show {
  opacity: 1;
  pointer-events: auto;
}

.material-symbols-outlined {
  font-variation-settings:
  'FILL' 0,
  'wght' 400,
  'GRAD' 0,
  'opsz' 24
}

 

JAVASCRIPT

const topBtn = document.querySelector('.arrow-box');

window.addEventListener('scroll', () => {
  if (window.scrollY > 200) {
    topBtn.classList.add('show');
  } else {
    topBtn.classList.remove('show');
  }
})
topBtn.onclick = function () {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

 

 

 

See the Pen btn_scroll_top by yw k (@yw-k) on CodePen.

 

반응형