¿Cómo puedo editar este código de las escuelas W3 para que se desplace más lento usando solo JQuery? Actualmente solo salta a la cima. ¿Hay alguna manera de reducir la velocidad para que el usuario pueda ver que en realidad está volviendo a la parte superior de la página? Idealmente, todo debería estar en JQuery si es posible.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_scroll_to_top
//Get the button var mybutton = document.getElementById("myBtn"); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { 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; } body { font-family: Arial, Helvetica, sans-serif; font-size: 20px; } #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn:hover { background-color: #555; } <body> <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> <div style="background-color:black;color:white;padding:30px">Scroll Down</div> <div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible <strong>when the user starts to scroll the page</strong>.</div>Editar para Pure jQuery
Estás buscando el método jQuery .animate(). Verificar:
https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
Están usando this.hash para encontrar el destino del desplazamiento suave. Puede omitirlo y reemplazarlo con '0' para desplazarse hacia arriba. Si eres nuevo en this.hash, mira:
Agregue jQuery a su encabezado html con:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>y reemplace su función superior con:
function topFunction() { $('html, body').animate({ scrollTop: 0 }, 500); }'500' es la duración de la animación de desplazamiento en milisegundos.
Puede intentar usar scrollTo con el comportamiento smooth https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo#examples
Aunque no funciona en Safari (veo que solo funciona desde Safari 14 y ahora), para Safari necesitas agregar un polyfill https://github.com/iamdustan/smoothscroll
Simplemente expanda su llamada scrollTop así:
window.scrollTo({top: 0, behavior: 'smooth'});