skip to Main Content

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

Answers


  1. 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();
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search