0

i have a <button> calls a function that scroll to the top of the page, how to appear this button automatically after 800px. using pure JavaScript Only?

<button class="button">
  GO To UP
</button>   
var button = document.querySelector(".button");

button.onclick = function () {
  window.scrollTo(0, 0);
};
Raghul SK
  • 1,256
  • 5
  • 22
  • 30
Ahmad Adel
  • 59
  • 4

1 Answers1

1

One approach could be having a hidden class on the button, and in css we can give the visibility of this class to be hidden.

.hidden {
  visibilty: hidden;
}

For handling the scroll functionality we can use this function

var button = document.querySelector(".button");

button.onclick = function(){
    window.scrollTo(0, 0);
}

window.addEventListener("scroll", () => {
    var y = window.scrollY;
    if (y >= 500) {
        button.classList.remove("hidden");
    } else {
        button.classList.add("hidden");
    }
});
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26