Hey I'm creating a Back to top button for my site for that I have made a code with requestAnimationFrame but the console is returning "Uncaught TypeError: Assignment to constant variable" and also the button disappears after page refresh (When a user reload the page after first time visit then the button disappears completely).
Need expert advice.
const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
document.addEventListener('DOMContentLoaded', function() {
const backToTopBtn = document.querySelector('[data-action="back-to-top"]');
const windowViewPortHeight = window.innerHeight;
const isRequestingAnimationFrame = false;
if (!backToTopBtn) {
return;
}
backToTopBtn.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
window.addEventListener('scroll', function() {
if (!isRequestingAnimationFrame) {
requestAnimationFrame(filterGoTopButtonVisibility);
isRequestingAnimationFrame = true;
}
});
function filterGoTopButtonVisibility(timestamp) {
const windowPageYOffset = window.pageYOffset || document.documentElement.scrollTop;
if (windowPageYOffset > windowViewPortHeight) {
backToTopBtn.classList.add('show');
isRequestingAnimationFrame = false;
} else {
backToTopBtn.classList.remove('show');
requestAnimationFrame(filterGoTopButtonVisibility);
}
}
});
div {
height: 1500px;
width: 100%;
}
.back-to-top {
position: fixed;
width: 45px;
height: 45px;
bottom: 20px;
left: 22px;
opacity: 0;
-webkit-transition: opacity 0.8s ease-in-out;
-moz-transition: opacity 0.8s ease-in-out;
-o-transition: opacity 0.8s ease-in-out;
transition: opacity 0.8s ease-in-out;
z-index: 9999;
border-radius: 7px;
outline: none;
border: none;
color: #e8576f;
border: 3px solid #e8576f;
background-color: #323757c7;
cursor: pointer;
}
.back-to-top.show {
opacity: 1;
}
.back-to-top:hover {
background-color: #282a3fdc;
}
.back-to-top .fa-angle-up {
font-size: 20px;
}
<div>
Scroll Down
</div>
<button class="back-to-top hide" data-action="back-to-top">
▲
</button>