<div class="to-up">Наверх</div>.to-up {
position: fixed;
bottom: 28px;
right: 28px;
display: none;
z-index: 22;
cursor: pointer;
}jQuery
jQuery(($) => {
$(window).scroll(function(){
if ($(this).scrollTop() > 780) $('.to-up').fadeIn();
else $('.to-up').fadeOut();
});
$('.to-up').click(function(){
$("html, body").animate({ scrollTop: 0 }, 566);
return false;
});
});или на JavaScript
document.addEventListener('DOMContentLoaded', () => {
let toTopBtn = document.querySelector('.to-up');
window.onscroll = function () {
if (window.pageYOffset > 580) {
toTopBtn.style.display = 'block'
} else {
toTopBtn.style.display = 'none'
}
}
// плавный скролл наверх
toTopBtn.addEventListener('click', function () {
window.scrollBy({
top: -document.documentElement.scrollHeight,
behavior: 'smooth'
});
});
});Ещё
<span>space!</span>
<a href="#" onclick="animateToTop(event)">to the top</a>
<span>more space!</span>
<a href="#" onclick="animateToTop(event)">to the top</a>
<span>even more space!</span>
<a href="#" onclick="animateToTop(event)">to the top</a>function animateToTop(e) {
e.preventDefault();
var scrollToTop = window.setInterval(function() {
var pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 16); // how fast to scroll (this equals roughly 60 fps)
}span {
display: block;
margin: 250px 0;
}Самое простое:
// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });