I'm trying to remove the event listener that I've added in for loop but it didn't work
Is there a way to do this with pure js?
for (let i = 0; i < drumPads.length; i++) {
drumPads[i].addEventListener("click", func)
function func() {
display.innerHTML = music[i][0];
sound.src = music[i][1];
sound.play();
}
}
Your function func should be defined outside the loop.
In your code the function func is block scoped and hence this wont be refering to the same memory when the user enters with "on" and "off" condition.
You can pass the index and some custom data from the target to the listner function by setting dataset of the target.
let drumPads = document.getElementsByClassName("drum-pads");
function Power(a) {
for (let i = 0; i < drumPads.length; i++) {
if (a === 'on') {
drumPads[i].dataset.index = i;
drumPads[i].addEventListener("click", func);
} else {
drumPads[i].removeEventListener("click", func);
}
}
}
function func(e) {
const targetIndex = e.currentTarget.dataset.index;
console.log('Triggered listner', targetIndex);
}
<div>
<button class="drum-pads">drum-pads 1</button>
<button class="drum-pads">drum-pads 2</button>
<button class="drum-pads">drum-pads 3</button>
<button class="drum-pads">drum-pads 4</button>
</div>
<div>
<button onclick="Power('on')">Toggle On</button>
<button onclick="Power('off')">Toggle Off</button>
</div>