scroll button js code example
Example 1: Scroll to the top of the page using JavaScript?
var topPage = document.getElementById(`top-page`)
topPage.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' })
window.onscroll = () => {
window.scrollY > 500
? (topPage.style.display = 'block')
: (topPage.style.display = 'none')
}
body {
background-color: #111;
height:5000px;
}
#top-page {
width: 50px;
position: fixed;
right: 30px;
bottom: 30px;
cursor: pointer;
color: white;
display: none;
}
<img id="top-page" src="https://svgshare.com/i/LW3.sv" alt="Top">
Example 2: javascript go to top of page
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
Example 3: simple button scrolling with this
$('#id a').on('click', function (e) {
var href = $(this).attr('href')
$('html, body').animate({
scrollTop: $(href).offset().top
}, '300')
e.preventDefault()
})