Search code examples
javascriptmaterialize

materialize collapsible: how to determine which section is open?


I have a materialize collapsible which works as expected. Something similar to:

<ul class="collapsible">
  <li>
   <div class="collapsible-header">Title1</div>
   <div class="collapsible-body" />
  </li>
  <li>
   <div class="collapsible-header">Title2</div>
   <div class="collapsible-body" />
  </li>
</ul>

In a later process, when pressing a button I need a javascript function to modify its behavior depending on which section is open.

How can I determine which section is open?

I guess one possibility would be to store in a hidden element the index of the section when it is selected but I don't know how to do it.


Solution

  • Materializecss add an active class to an open collapsible item by itself. So you can use it to understand which collapsible item is open.

    You can use this jquery code :

    $(document).on("click","ul.collapsible li", function(){
    
      var elem = document.querySelectorAll("ul.collapsible li");
      var index = "none"
    
      for (var i = 0; i < elem.length; i++) {
        if (elem[i].className == "active") {
            index = i;
        }
        document.getElementById("show").innerHTML = index;
      }
    
    })
    

    This code show index of opened collapsible item for you.

    Here is complete example : jsFiddle