Hello everyone!
Can someone interpret this code bloc to me?
especially this part accordion[i], thank!
// Select the element and store it in a variable
const accordion = document.getElementsByClassName("accordion");
let i; // counter
for (i = 0; i < accordion.length; i++) {
accordion[i].addEventListener("click", function () {
/* Toggle between adding and removing the 'active' class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
const panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
I’ve rewritten the code with comments for it to make more sense.
// take the element with the class of "accordion", and store it in
// a variable called "accordion" - this will make the variable be
// an array since the accordion element has child elements
// and the document.getElementsByClassName grabs
// everything the accordion contains
const accordion = document.getElementsByClassName("accordion");
let i;
// go through each element of the accordion variable (array)
for (i = 0; i < accordion.length; i++) {
// add an EventListener to each element of the array
// that listens for a click being made on the element
accordion[i].addEventListener("click", function () {
// when clicked, if the element does not have the class
// of active on it, then add it. If it does have the class
// of active, then take it out
this.classList.toggle("active");
// grab the element that comes directly after the one that
// was just clicked, and store it in a variable called panel.
// If panel has a maxHeight, make it null, if it doesn't have
// a maxHeight, then set the maxHeight to whatever the
// panel's scrollHeight is
const panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
1 Like