what wrong on scroll top functionality

36 Views Asked by At

Is this correct way to add scroll top functionality?

function toTop(){
  const topTrigger = document.querySelector('.back-to-top');

  topTrigger.addEventListener('click', () => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: 'smooth',
    });
  });
}
toTop();
2

There are 2 best solutions below

0
Usitha Indeewara On

Your code seems to be working correctly. Somehow if it doesn't work, try calling toTop() when the DOM content is loaded:

document.addEventListener('DOMContentLoaded', function() {
  toTop();
});
0
Joyal George K J On

HTML:

<div class="up">
  <a href="#">
    <i class="bi bi-chevron-double-up"></i>
  </a>
</div>

JS:

window.addEventListener("scroll", () => {
  if (window.scrollY > 300) {
    document.querySelector(".up").style.display = "flex";
  } else if (window.screenY < 300) {
    document.querySelector(".up").style.display = "none";
  }
});

This will work, Here JS is used to toggle the display.