Move scrollbar to the bottom of the page in LWC

lightning-web-componentsscrolling

I am trying to display the scroll bar at the bottom of the page instead of displaying at the top of the page along with the data for an LWC component. Similar to mobile device, this is what I have

   <div class="slds-scrollable_y" >                                                          
       <template for:each={data} for:item="data">       
           <div key={data.Id}>
               <c-child-component data={data}></c-child-component>                        
           </div>
        </template>
     </div>

which tags can I use in CSS to display the scrollbar at the bottom of the div just like texting from phone the scrollbar starts at bottom?

Best Answer

You simply need to use scrollTop/scrollHeight in a script. Here's an example:

import { LightningElement } from "lwc";

export default class App extends LightningElement {
  data = [...Array(100).keys()].map(value => ({Id: value, value: `Message ${value}`}));
  renderedCallback() {
    const scrollArea = this.template.querySelector('[data-scroll-area]')
    scrollArea.scrollTop = scrollArea.scrollHeight
  }
}

Demo.

Related Topic