I’m trying to build a simple toggle class with JS, but struggle to pass variables to eventlisteners as I need also to remove them.
Is it possible to pass btn
and possibly more parameters into handleClick()
? I can’t pass directly or use anonymous function as I need to remove listeners in destroy()
.
If I use e.target
I sometimes receive span
or svg
as target so ideally I want to pass btn
variable directly.
html:
<div class="toggle" id="toggle-1">
<button class="toggle-button">
<span>open toggle</span>
<svg>...</svg> <!--icon -->
</button>
<div class="toggle-content" hidden>
...content
</div>
</div>
class Toggle {
constructor(element) {
this.el = document.querySelector(element);
this.addListeners();
}
addListeners() {
const btn = this.el.querySelector('button');
btn.addEventListener('click', this.handleClick) // <!--- how do I pass btn here?
}
handleClick(btn) { <!--- how do I receive btn here?
const panelID = btn.closest('.toggle').id;
this.open(panelID);
}
open(panelID) {
// open functionality
}
destroy() {
const btn = this.el.querySelector('button');
btn.removeEventListener('click', handleClick)
}
}