2

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.

2

add this in goToTop function remove everything else

  this.template.querySelector('.test').scrollTop=0;

and in the html class assign class name test like

<div class='test' style="overflow: auto; position: fixed; top: 0; left: 0; right: 0; bottom: 0; " onscroll={onScroll}> 
6
  • it is working as expected in the playground but in real time I am getting this error Uncaught TypeError: this.template.querySelectorAll(...)[0].scrollTo is not a function, could you please suggest on it – gs650x Nov 11 '19 at 8:09
  • i have updated my answer @gs650x – User6670 Nov 12 '19 at 6:54
  • Thank you, but we cannot add scroll behavior with this. – gs650x Nov 12 '19 at 6:56
  • can you share your code.i just deployed this its working fine for me – User6670 Nov 12 '19 at 7:01
  • It works fine but how to add scroll behavior with the same? – gs650x Nov 12 '19 at 7:02
1

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;
}
0

To make the scrollTop = 0 to work the container div has to have an internal scroll. Which we can get by either giving a height via px or via vh.

Try that out it should work. I was facing a similar issue while adding LWC inside Flexi Page. The Flexi page has its own scroller but for that, the scrollTop doesn't work. But if we create a separate scroller at the top-level div then the scrollTop starts to work.

Check this out. I have created this and it works perfectly fine for me: https://webcomponents.dev/edit/3vpWJ46hxykfPSACfuNN

1
  • While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. – identigral Jan 20 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.