简体   繁体   中英

Scroll to bottom of div in Polymer on component ready

I am working on a Polymer component where I have a chat box in which I load messages from my Firebase database. I want the div containing the messages to be scrolled to the bottom when the component is loaded so the user can see the latest messages.

However, I am unable to scroll to the bottom of a div in my Polymer component in ready() or attached() lifecycle methods. The only time I see the scrolling occur correctly is when I manually trigger the scroll by tapping on my "submit" button (code below).

In my Polymer 2.0 element, I have the following code in my component:

HTML

  <!-- CONTAINER TO DISPLAY MESSAGES -->
  <div id="messages_container">
    <template is="dom-repeat" items="{{messages}}" as="message">
          [[message.name]]: [[message.text]]
    </template>
  </div>

  <!-- MESSAGE INPUT -->
  <textarea
    placeholder="Type your message here"
    on-input="_onMessageInput">
  </textarea>
  <paper-button raised id="submit"
    on-tap="_submitMessage">
    Send
  </paper-button>

JS

ready(){
  super.ready();
  this._scrollToBottom(); //calling from ready or attached does not scroll the div to the bottom  

  //I have also tried Polymer.RenderStatus.afterNextRender(this, () => { this._scrollToBottom(); }); but that does not cause scrolling to occur consistently
}

/**
 * Observer triggered when messages are written to Firebase database
 */
_onMessagesChanged(){ 
  this._scrollToBottom();
}

_scrollToBottom(){
  this.$.messages_container.scrollTop = 
  this.$.messages_container.scrollHeight;
}

_submitMessage(){
  // store message in Firebase database code not shown
  // this triggers onMessagesChanged(), which then correctly scrolls the div to the bottom
}

I am seeing that the scrolling to bottom behavior happens only when I tap on the submit button to manually trigger _onMessagesChanged . However, I am not getting the scrolling behavior on initial load of my component.

Any help would be appreciated.

Try debounce() or simply setTimeout() to delay the invocation of your _scrollToBottom() . https://www.polymer-project.org/2.0/docs/upgrade#common-utility-apis

You can set up a listener for when the dom-repeat changes, and therefor would never have to update it manually. Put this after your properties declaration:

listeners: {'dom-change': '_scrollToBottom'},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM