Skip to content

Instantly share code, notes, and snippets.

@RussellJapheth
Last active July 13, 2023 08:41
Show Gist options
  • Select an option

  • Save RussellJapheth/849caea6aef04ecc957642e7009349ec to your computer and use it in GitHub Desktop.

Select an option

Save RussellJapheth/849caea6aef04ecc957642e7009349ec to your computer and use it in GitHub Desktop.
Accordion
const accordions = document.querySelectorAll(".accordion");
accordions.forEach((accordion) => {
accordion.addEventListener("click", function () {
// Remove "active" class from all accordions
accordions.forEach((acc) => {
if (acc !== accordion) {
// remove active class
acc.classList.remove("active");
// collapse the panel by setting the max height to null
let panel = acc.nextElementSibling;
if(panel.style.maxHeight) {
panel.style.maxHeight = null;
}
}
});
// Toggle "active" class on the clicked accordion
accordion.classList.toggle("active");
let panel = accordion.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
});
var accordions = document.querySelectorAll(".accordion");
for (var i = 0; i < accordions.length; i++) {
var accordion = accordions[i];
accordion.addEventListener("click", function () {
// Remove "active" class from all accordions
for (var j = 0; j < accordions.length; j++) {
var acc = accordions[j];
if (acc !== accordion) {
acc.classList.remove("active");
// collapse the panel by setting the max height to null
let panel = acc.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
}
}
}
// Toggle "active" class on the clicked accordion
accordion.classList.toggle("active");
let panel = accordion.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
/*
In this version we use var instead of const to declare the accordions, accordion, i, and j variables.
We then use a for loop to iterate over the accordions collection.
Inside the loop, we attach a click event listener to each accordion element.
The for loop is used again to remove the "active" class from all accordions except the clicked one.
Finally, we toggle the "active" class on the clicked accordion using the classList.toggle method,
just like in the previous implementation.
*/
@amp-bay
Copy link

amp-bay commented Jul 10, 2023

can you please write the code with the panel class in view too?

@RussellJapheth
Copy link
Author

Add comments and update panel code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment