<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accordion Summary Example</title>
<style>
.data-accordion--summary-container {
margin-bottom: 10px;
padding: 10px;
background-color: lightblue;
cursor: pointer;
}
.dropdown {
display: none;
background-color: lightcoral;
padding: 10px;
}
</style>
</head>
<body>
<div class="data-accordion--summary-container">
Summary 1
<div class="dropdown">
Dropdown content 1
<div class="data-accordion--summary-container">
Subsummary 1
<div class="dropdown">
Subdropdown content 1
</div>
</div>
<div class="data-accordion--summary-container">
Subsummary 2
<div class="dropdown">
Subdropdown content 2
</div>
</div>
</div>
</div>
<div class="data-accordion--summary-container">
Summary 2
<div class="dropdown">
Dropdown content 2
</div>
</div>
<div class="data-accordion--summary-container">
Summary 3
<div class="dropdown">
Dropdown content 3
</div>
</div>
<script>
// Function to find the closest ancestor with class "data-accordion--summary-container"
function findClosestSummaryContainer(element) {
while (element) {
if (element.classList.contains('data-accordion--summary-container')) {
return element;
}
element = element.parentElement;
}
return null;
}
// Attach click event listener to the document body
document.body.addEventListener('click', function(event) {
// Find the closest ancestor with class "data-accordion--summary-container"
var summaryContainer = findClosestSummaryContainer(event.target);
if (summaryContainer) {
// Toggle the visibility of the dropdown associated with this container
var dropdown = summaryContainer.querySelector('.dropdown');
if (dropdown) {
// Hide dropdowns of other containers
document.querySelectorAll('.dropdown').forEach(function(otherDropdown) {
if (otherDropdown !== dropdown) {
otherDropdown.style.display = 'none';
}
});
// Toggle the visibility of this container's dropdown
dropdown.style.display = (dropdown.style.display === 'block') ? 'none' : 'block';
}
}
});
</script>
</body>
</html>
.dropdown.show {
display: block;
}
const accordionItemSelector = '.data-accordion--summary-container';
const contentSelector = '.dropdown';
const activeClass = 'show';
document.body.addEventListener('click', ({ target: t }) => {
if (t.matches(accordionItemSelector)) {
document.querySelectorAll(contentSelector).forEach(n => {
if (!n.contains(t) && !t.contains(n)) {
n.classList.remove(activeClass);
};
});
t.querySelector(contentSelector).classList.toggle(activeClass);
}
});