I created simple collapse and expand mechanism by removing or adding the ‘active’ class. The removing mechanism works perfectly fine but I have a problem with adding active class on click:
const panelActive = document.querySelector('.panel');
const panelInactive = document.querySelectorAll('.panel:not(.active)');
// console.log(panelInactive);
const collaps = (event) => {
console.log(event);
panelActive.classList.remove('active');
};
const expand = (panel) => {
console.log(panel);
console.log(panel.classList);
panel.classList.add('active');
};
panelInactive.forEach((panel) => {
panel.addEventListener('click', collaps);
panel.addEventListener('click', expand);
});
When the expand function is called, the .classList function returns an undefine value instead of a list of classes:
So I think thats the reason why it does not work at all.
Do you know how to fix it?
2
Answers
This:
Doesn’t pass any explicit arguments to
expand()
. The default implicit argument for an event handler is anevent
object. (In this case aPointerEvent
.) Which you are observing when you do this:And further observing that the
event
object has noclassList
property when you log this:The
expand()
function is expecting a "panel" to be provided, but you haven’t provided one. You can do so manually:As an aside, the code is likely to have other problems as well. For example, the
collaps()
function will only ever "collapse" the "panel" that was originally expanded. No other panels would be affected.You can correct this by getting the "active panel" in the function itself, rather than only once when the page loads:
Keep it easy – remove the
active
class from all panels on click, and add it to the clicked one: