I have modal with back on top button that is supposed to appear, when user scrolls modal 30px, and disappear when use comes back on top of modal by himself. But unfortunately it doesn't work as expected. Button appears after scrolling 30px, but never disappears.
// Logic for get to top button
let getToTopButton = document.getElementById('btn-back-to-top');
// When user scrolls down 30px, show the button
document
.getElementById('myFlix-react-case-study')
.addEventListener('scroll', scrollFunction);
function scrollFunction() {
if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 30) {
getToTopButton.style.display = 'block';
} else {
getToTopButton.style.display = 'none';
}
}
.modal-container {
position: fixed;
padding: 20px;
box-sizing: border-box;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
/* to show it above other content */
z-index: 999;
/* to allow scrolling if the screen is not high enough*/
overflow: scroll;
/* this is used to center the modal */
display: grid !important;
text-align: center;
}
.case-study-modal {
margin: 80px auto 0px;
display: inline-block;
box-sizing: border-box;
background: #fff;
padding: 20px 30px;
width: 100%;
max-width: 1100px;
text-align: left;
border-radius: 15px;
color: var(--primary-color);
position: relative;
}
.button-up-container {
position: absolute;
right: 38px;
top: 600px;
width: 41px;
}
#btn-back-to-top {
position: fixed;
background: var(--primary-color) linear-gradient(to bottom right, var(--primary-color) 25%, var(--accent-color));
border: none;
border-radius: 10px;
color: var(--font-color);
padding: 8px 16px;
font-size: 22px;
display: none;
}
<div id='myFlix-react-case-study' class="d-none modal-container ">
<div class='case-study-modal'>
<div class="button-up-container">
<button type="button" id="btn-back-to-top">
<i class="fas fa-arrow-up"></i>
</button>
</div>
<div class="modal-title">
<p>
Some title
</p>
</div>
<div class="modal-content">
<p>
Some content
</p>
</div>
Appreciate for your advices
I tried to swap adding style display: block
and style display: none
it behaved a little better, but still 'back to top button' didn't disappear. I also tried to use scrollHeight instead scrollTop but it confused me even more.
I got expected behaviour when I used scrollTop specifically for modal-container, which I reached by id, Instead of using scrollTop for body or documentElement. So I changed only JavaScript for 'scrollFunction' like this:
function scrollFunction() {
console.log('modal scrolled');
if (
document.getElementById('myFlix-react-case-study').scrollTop > 50
) {
getToTopButton.style.display = 'block';
} else {
getToTopButton.style.display = 'none';
}
}