Back To Top Button Behaviour

Viewed 93

Hello I am trying to figure out what I can use in order for my "Back to top" button to scroll smoothly. I do not want to use the regular "scroll-behaviour:smooth;" as I am using an animated css library in order to utilize other animation features like "fade in and out". With that said what exactly do I add to the following code in order to give my "Back to top" button a smooth scroll.

//Get the button
var mybutton = document.getElementById("btnToTheTop");

// When the user scrolls down 150px from the top of the document, show the button
window.onscroll = function() { scrollFunction() };

function scrollFunction() {
    if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {
        mybutton.style.display = "block";
    } else {
        mybutton.style.display = "none";
    }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

1 Answers

use scrollIntoView():

  const smoothScroll = () => {
    const el = document.querySelector("btnToTheTop");
    el.scrollIntoView({ block: "center", behavior: "smooth" });
  };

and put it in onClick

Related