rohan_vg rohan_vg - 7 months ago 32
HTML Question

HTML5 - Automatically close all the other <details> tags after opening a specific <details> tag

Here is my code ->
JSFiddle

<!DOCTYPE html>
<html>
<body>

<details>
<summary>1</summary>
Demo 1
</details>

<details>
<summary>2</summary>
Demo 2
</details>

<details>
<summary>3</summary>
Demo 3
</details>

</body>
</html>


What I want to do is -- if the details of any single
<details>
tag is open and I open/view another
<details>
tag, then the earlier one should close/hide/minimize.

How can this be achieved?

P.S. The
<details>
tag is only supported in Chrome & Safari browser.

Answer

I have come up with a solution. Please correct me if this is a wrong approach.

I added an onclick event to all of the details tag and made a function thisindex(this) which returns the index of the clicked tag and the obtained index number is then passed to the another function closeAll() which minimizes/closes all the other open tags except for one whose index matches with what we obtained earlier.

Here is the code: JS Bin Link

<!DOCTYPE html>
<html>
  <body>

  <details onclick="closeAll(thisindex(this));">
      <summary>1</summary>Demo 1
  </details>

  <details onclick="closeAll(thisindex(this));">
      <summary>2</summary>Demo 2
  </details>

  <details onclick="closeAll(thisindex(this));">
      <summary>2</summary>Demo 3
  </details>

  <script>

      function thisindex(elm){
        var nodes = elm.parentNode.childNodes, node;
        var i = 0, count = i;
        while( (node=nodes.item(i++)) && node!=elm )
        if( node.nodeType==1 ) count++;
        return count;
      }

      function closeAll(index){
        var len = document.getElementsByTagName("details").length;

        for(var i=0; i<len; i++){
          if(i != index){
            document.getElementsByTagName("details")[i].removeAttribute("open");
          }
        }
      }

  </script>

  </body>
</html>

Same with the help of jQuery

$(document).ready(function(){
  $('details').click(function (event) {
    var index = $('details').index(this);
    var len = $("details").length;
    for(var i=0; i<len; i++){
      if(i != index){
        $("details")[i].removeAttribute("open");
      }
    }
  });
});

Kindly suggest me a better approach if this not up to the mark.