With Javascript you can use the scrollIntoView() method.
If you want to use jQuery you can use scrollTop.
<!DOCTYPE html>
<html>
<head>
<title>Scroll to Top Example</title>
</head>
<body>
<div style="height: 1000px;">Scroll down...</div>
<button id="scroll-to-top">Back to top</button>
<script>
const scrollToTopButton = document.getElementById('scroll-to-top');
// When the button is clicked, scroll to the top
scrollToTopButton.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// Show the button when the user scrolls down
window.addEventListener('scroll', () => {
if (window.scrollY > 500) {
scrollToTopButton.style.display = 'block';
} else {
scrollToTopButton.style.display = 'none';
}
});
</script>
</body>
</html>
<<!DOCTYPE html>
<html>
<head>
<title>Scroll to Top Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div style="height: 1000px;">Scroll down...</div>
<button id="scroll-to-top">Back to top</button>
<script>
$(document).ready(function() {
// When the button is clicked, scroll to the top
$('#scroll-to-top').click(function() {
$('body, html').animate({
scrollTop: 0
}, 500);
});
// Show the button when the user scrolls down
$(window).scroll(function() {
if ($(this).scrollTop() > 500) {
$('#scroll-to-top').fadeIn();
} else {
$('#scroll-to-top').fadeOut();
}
});
});
</script>
</body>
</html>