I am trying to add an variableName.addEventListener("transitionend", function ()
to all of my classes named .aboutCollapsible
. The code provided below only works on the first element due to it being querySelector
and not querySelectorAll
.
JavaScript Code: Reasoning for writing all of the code is for context, in case that is required to understand the question.
//var coll = document.getElementsByClassName("collapsible");
const el = document.querySelector(".aboutCollapsible");
//var i;
//
//for (i = 0; i < coll.length; i++) {
// coll[i].addEventListener("click", function () {
// this.classList.toggle("active");
// var content = this.nextElementSibling
// if (content.style.maxHeight < "100%") {
// content.style.maxHeight = content.scrollHeight + "px";
el.addEventListener("transitionend", function () {
content.style.maxHeight = "100%"
});
// } else {
// content.style.transitionDuration = "0s"
// content.style.maxHeight = content.scrollHeight + "px";
// content.style.maxHeight = content.scrollHeight + "px";
// content.style.transitionDuration = "0.5s"
// content.style.maxHeight = "0px";
el.addEventListener("transitionend", function () {
content.style.maxHeight = null
content.style.transitionDuration = null
});
// }
// });
//}
I get the following error when changing querySelector
to querySelectorAll
:
TypeError: el.addEventListener is not a function
How would I go about solving the issue of adding addEventListener("transitionend", function () {
to all of my classes named .aboutCollapsible
?
UPDATE: This seems to work, however, isn't there a better way. Do I really have to run a forEach loop every time it the click is triggered? Can I just not call the transitionend function instead?
// Button Collapsible
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.nextElementSibling
if (content.style.maxHeight < "100%") {
content.style.maxHeight = content.scrollHeight + "px";
document.querySelectorAll(".aboutCollapsible").forEach(e => e.addEventListener("transitionend", function(){
content.style.maxHeight = "100%"
}));
} else {
content.style.transitionDuration = "0s"
content.style.maxHeight = content.scrollHeight + "px";
content.style.maxHeight = content.scrollHeight + "px";
content.style.transitionDuration = "0.5s"
content.style.maxHeight = "0px";
document.querySelectorAll(".aboutCollapsible").forEach(e => e.addEventListener("transitionend", function(){
content.style.maxHeight = null
content.style.transitionDuration = null
}));
}
});
}