RobC RobC - 12 days ago 5
Javascript Question

How to show last item visible in iron-list?

I'm creating chat page. And I'm updating message with iron-list. Everytime I pusshed message to

array
iron-list
added into that template. Now I want last appended message visible in the bottom. Currently user have to scroll to bottom and see that message.

// Polymer
properties: {
messageItem: { type: Array, notify: true, value: function() { return []; } },
},

# Html
<iron-list items="[[messageItem]]" as="item">
<template>...</template>
</iron-list>


Push code:

this.push('messageItem', {name: 'bot', message: event.data});


What necessary steps should I take to achieve this ?

Answer

You could set <iron-list>.scrollTop to its scrollHeight after adding an item to the list and allowing it to render. You could use Polymer.RenderStatus.afterNextRender() for that purpose:

// template
<iron-list id="list">...</iron-list>

// script
_addItem: function() {
  this.push('items', ...);
  Polymer.RenderStatus.afterNextRender(this, () => {
    this.$.list.scrollTop = this.$.list.scrollHeight;
  });
}

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties: {
      items: {
        type: Array,
        value: () => [0,1,2]
      }
    },
    _addItem: function() {
      this.push('items', this.items.length);
      this._scrollToBottom();
    },
    _scrollToBottom: function() {
      Polymer.RenderStatus.afterNextRender(this, () => {
        this.$.list.scrollTop = this.$.list.scrollHeight;
      });
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-list/iron-list.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <style>
        iron-list {
          border: solid 1px red;
          height: 100px;
        }
      </style>
      <button on-tap="_addItem">Add item</button>
      <iron-list id="list" items="[[items]]">
        <template>
          <div>[[item]]</div>
        </template>
      </iron-list>
    </template>
  </dom-module>
</body>

codepen