Monaca Onsen UI Discord Chat Github Repo

How do I close other opened expandable items when opening a new one?



  • Is there a callback functionality for expandable items?
    The reason why I’m asking is that I want to close other ‘opened’ item when opening a new one.


  • administrators

    There’s no callback functionality for expandable list items, but one way you could get this to work is to override the showExpansion function. Here is an example:

    https://codepen.io/emccorson/pen/MWwjdmE

    HTML

    <ons-page>
      <ons-list>
        <ons-list-item expandable>
          One
          <div class="expandable-content">Expandable content</div>
        </ons-list-item>
        
        <ons-list-item expandable>
          Two
          <div class="expandable-content">Expandable content</div>
        </ons-list-item>
        
        <ons-list-item expandable>
          Three
          <div class="expandable-content">Expandable content</div>
        </ons-list-item>
      </ons-list>
    </ons-page>
    

    JS

    ons.ready(() => {
      document.querySelectorAll('ons-list-item').forEach(listItem => {
        const showExpansion = listItem.showExpansion.bind(listItem);
        
        listItem.showExpansion = () => {
          document.querySelectorAll('ons-list-item.expanded').forEach(expandedListItem => {
            if (expandedListItem !== listItem) {
              expandedListItem.hideExpansion();
            }
          });
          showExpansion();
        }
      });
    });
    


  • @emccorson

    Thank you very much.
    When I tried it for the first time I found out that it does not seem to work on dynamically generated lists. So what I did was to remove the ons-ready and converted it to a function to be invoked each time a new content is generated. Now its working!