[SalesForce] A button to scroll at the top of the page in LWC

Below Playground I have code with the button to scroll at the top of the page and conditionally render the button when user scrolled down. Now if I remove the custom render thing then button works as expected but when I add the custom css for conditional rendering then button stopped working,

Playground

On above playground when you scroll down, a button will appear at the bottom left but when you click on it won't scroll at the top.

Best Answer

You can even use window.scrollTo option, if you want to scroll till top.

topFunction(){
    const scrollOptions = {
        left: 0,
        top: 0,
        behavior: 'smooth'
    }
    window.scrollTo(scrollOptions);
}

HTML (add this at end):

<lightning-button-icon icon-name="utility:arrowup" class="topButton" onclick={topFunction}
                       variant="brand" alternative-text="ArrowUp">
</lightning-button-icon>

CSS:

.topButton {
    position: fixed;
    bottom: 20px;
    right: 30px;
    z-index: 99;
    font-size: 18px;
    border: none;
    outline: none;
    cursor: pointer;
    border-radius: 4px;
}

.topButton:hover {
    background-color: #555;
}
Related Topic