javascript scroll back to top function is not working

93 Views Asked by At

I need to scroll to the top of the page. Here is my code and doesn't work and I don't understand why.

Are there any features that are deprecated and don't work in Chrome?

I use Chrome version 109.

window.onscroll = () => {
  toggleTopButton();
}

document.getElementById('back-to-up').addEventListener('click',function(){
  window.scroll({top:0, left:0, behavior:'smooth'});
});

function toggleTopButton() {
  if (document.body.scrollTop > 20 ||
      document.documentElement.scrollTop > 20) {
    document.getElementById('back-to-up').classList.remove('d-none');
  } else {
    document.getElementById('back-to-up').classList.add('d-none');
  }
}
<button class="scroll-top" id="back-to-up">
  <i class="fa fa-arrow-up" aria-hidden="true"></i>
</button>

.scroll-top {
  position: fixed;
  bottom: 25px;
  right: 25px;
  z-index: 99;
  outline: none;
  background-color: #efefef;
  border: 1px solid #333;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

.d-none {
    display: none!important;
}

I need some help here.

I looked through the posts here and did not find the cause. I've tested in many ways and I don't know what's wrong.

1

There are 1 best solutions below

2
Pavel Sturov On

I have prepared a simple working snippet, you can see it below. Hope this can help!

Best regards

const topUpBtn = document.getElementById('btn')

topUpBtn.addEventListener('click', () => {
  window.scrollTo({top: 0, behavior: 'smooth'})
})

window.addEventListener('scroll', () => {
if (document.documentElement.scrollTop > 20) {
  topUpBtn.style.display = 'block'
} else {
  topUpBtn.style.display = 'none'
}
})
body {
  height: 1000px
}

#btn {
  position: fixed;
  display: none;
  bottom: 50px;
  right: 50px;
}
<button id="btn">up</button>