'Adding a button to scroll to top

I am trying to detect when the user scroll down...and show a button to scroll to top when clicked I didn't create a directive, I found it very difficult to understand so I am using Content

I have managed to scroll to top when the button is clicked

.ts

scrollToTop(){
var distance = this.content.scrollTop;

if (distance > 0){
 this.content.scrollToTop();
 } 
}

but I dont know how to show and hide the button.... currently it is shown in the constructor this.showButton = true; I want to show the button when scrollTop changes



Solution 1:[1]

You can try using Content ionScrollStart event or ionScroll event.

In html,

<ion-content (ionScrollStart)="showScrollButton()">

and in component,

showScrollButton(){
  this.showButton=true;
}

Solution 2:[2]

const scrollTop = function (){
        const scroll_btn = document.querySelector('#scrollbtn');

            const rootElement = document.documentElement;
            const TOGGLE_RATIO = 0.80;

            function handleScroll() {
            // do something on scroll
            const scrollTotal = rootElement.scrollHeight - rootElement.clientHeight
                
                if ((rootElement.scrollTop / scrollTotal) > TOGGLE_RATIO) {
                //show button
                scroll_btn.classList.add("showBtn")
                
            } else {
                //hide button
                scroll_btn.classList.remove("showBtn")
                

        }
    }
    scroll_btn.addEventListener("click", scrollToTop)

            function scrollToTop() {
            //scroll to top logic
            rootElement.scrollTo({
                top: 0,
                behavior: "smooth"
                })
            }
    
    document.addEventListener("scroll", handleScroll)
                
};

scrollTop();
html{
    background: yellow;
    block-size: 200vh;
    }
.scrollbtn{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 5rem;
    height: 4rem;
    color: var(--important);
    background-color: var(--main-color);
    font-weight: 600;
    position: fixed;
    bottom: 2rem;
    right: 2rem;
    border-radius: 50%;
    font-size: 1.5rem;
    z-index: 1000;
    opacity: 0;
    
}

.scrollbtn:hover{
    background-color: rgb(3, 141, 139);
    /*hanges the color of the button on hover*/
}

#scrollbtn.showBtn{
  /*toogles the button on js condition being true*/
    opacity: 1;
    transition: opacity 1s, transform 1s;
}
<html>
  <h1>This is an H1 tag </h1>
  <button class="scrollbtn" id="scrollbtn" title="Scroll to top">Top</button>
</html>

I hope this answers your question.

Thanks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mfoniso Ukpabio