Thomas K Thomas K - 5 months ago 121
Javascript Question

Polymer Multiple Iron-Collapse

The polymer docs aren't clear on how to create a multiple toggle using iron-collapse. Is there an easy way to get each item to toggle? I had a look at multiple iron-collapse not working, expands only first but I could not get it to work. Maybe something has changed in polymer since then. Below is an example of the code I am using.

<div on-click="toggle"><paper-item><a class="paper-item-link"><strong>List Items</strong></a></paper-item></div>
<iron-collapse id="collapse">
<div>Content</div>
</iron-collapse>

<div on-click="toggle"><paper-item><a class="paper-item-link"><strong>List Items</strong></a></paper-item></div>
<iron-collapse id="collapse">
<div>Content</div>
</iron-collapse>

toggle: function() {
this.$.collapse.toggle();
},

Answer

Polymer's automatic node finding maps nodes by their IDs, but you have two nodes with the same ID, so only the last one encountered would be mapped to that ID (i.e., this.$.collapse refers to the second iron-collapse in your example). Also, since your click-handler refers to the same iron-collapse, both paper-items would toggle the same iron-collapse when clicked.

The quickest solution would be to use unique node IDs for each iron-collapse and to use unique click handlers:

<head>
  <base href="https://polygit.org/polymer+1.5.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="paper-item/paper-item.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <div on-click="toggle1">
        <paper-item>
          <a class="paper-item-link"><strong>List Items</strong></a>
        </paper-item>
      </div>
      <iron-collapse id="collapse1">
        <div>Content</div>
      </iron-collapse>

      <div on-click="toggle2">
        <paper-item>
          <a class="paper-item-link"><strong>List Items</strong></a>
        </paper-item>
      </div>
      <iron-collapse id="collapse2">
        <div>Content</div>
      </iron-collapse>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({
          is: 'x-foo',
          toggle1: function() {
            this.$.collapse1.toggle();
          },
          toggle2: function() {
            this.$.collapse2.toggle();
          }
        });
      });
    </script>
  </dom-module>
</body>

codepen