How To Create a Scroll Back To Top Button with JavaScript
window.onscroll = function(){scrollFunction()};
let scroll = document.getElementById(‘scroll-top-btn’);
if(scroll){
scroll.style.display = “none”;
}
function scrollFunction(){
if(document.body.scrollTop > 180|| document.documentElement.scrollTop > 180){
//document.getElementById(‘menu’).style.cssText = “position: fixed; width: 100%; z-index: 9; background: #fff; top: 0;”;
if(document.getElementById(‘menu’).classList.contains(‘scroll-menu-active’)==false){
//document.getElementById(‘menu’).classList.add(‘scroll-menu-active’);
document.getElementById(‘menu’).className += ” “+”scroll-menu-active”;
}
}else{
document.getElementById(‘menu’).classList.remove(‘scroll-menu-active’)
}
if(document.body.scrollTop > 20|| document.documentElement.scrollTop > 20){
document.getElementById(‘scroll-top-btn’).style.display = ‘block’;
} else{
document.getElementById(‘scroll-top-btn’).style.display = “none”;
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
// document.body.scrollTop = 0; // For Safari
// document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
jQuery(‘html,body’).animate({scrollTop:0}, 800);
}
5 thoughts on “How To Create a Scroll Back To Top Button with JavaScript”
Comments are closed.