Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
remove eventListener from for loop

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();
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!