LEE
LEE

Reputation: 3605

Scroll to bottom automatically using vanilla Javascript/CSS - Polymer

I don't want to use JQuery to do this. Currently, I've created a listview using Polymer. I'm using <template is="dom-repeat"> inside a parent div with a class of list.

The CSS is as follows. As I add new items to the list, I would like the list to scroll to the bottom automatically. Is that possible?

.list {
  @apply(--layout-flex);
  @apply(--layout-vertical);
  position: relative;
  overflow: auto;
}

Upvotes: 0

Views: 725

Answers (1)

tony19
tony19

Reputation: 138256

You can set the div's scrollTop to scrollHeight in order to automatically scroll to the bottom:

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties: {
      items: {
        type: Array,
        value: () => []
      }
    },
    _addItem: function() {
      this.push('items', this.items.length+1);
      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">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <style>
        #list {
          border: solid 1px gray;
          width: 100%;
          height: 100px;
          overflow: auto;
        }
      </style>
      <button on-tap="_addItem">Add item</button>
      <div id="list">
        <template is="dom-repeat" items="[[items]]">
          <div>[[item]]</div>
        </template>
      </div>
    </template>
  </dom-module>
</body>

codepen

Upvotes: 2

Related Questions