JQuery returns collections of elements matching a query, and calling a method on a collection performs the method on each member - the reason they all open at once.
- To open
details
one at time you can iterate through the collection and open the first one that is not open.
- To close the last one opened you can create an array from the
details
collection, reverse the array, create a new collection from the array, find the find the first opened element in the reversed collection and close it (phew).
- To close all opened elements, simply remove the
open
attribute from the entire details
collection.
Note that open
is an attribute without a value - the details element is open if the attribute is present and closed if it is absent.
Unfortunately jQuery doesn't have a "hasAttribute" function, and while work-arounds have been devised, many of them do not apply to attributes without a value. However the native hasAttribute
element method has been around longer than the <details>
element and is supported in all modern browsers.
So using jQuery (mostly) you could try the following. Type 'a' to open a single element, 'c' to close the last open element, or 'z' to close all open (details) elements:
document.onkeyup = function(e) {
var e = e || window.event;
if (e.which == 65) { // 'a' - open one
$('details').each( function() {
if( this.hasAttribute("open")) {
return true;
}
$(this).attr("open", true);
return false;
});
}
else if(e.which == 67) { // 'c' - close one
$($('details').get().reverse()).each( function() {
if( this.hasAttribute("open")) {
$(this).removeAttr("open");
return false;
}
});
}
else if(e.which == 90) { // 'z' - close all
$('details').removeAttr('open');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<details>
<summary>Details1</summary>
test1
<details>
<summary>Details2</summary>
test2
<details>
<summary>Details3</summary>
test3
</details>
</details>
</details>