Disabling eventListener after a certain number of clicks

Viewed 36

How can I disable an event listener after a certain number of clicks are received?

I think the below code is wrong as I am calling for event Listener to be disabled from within the event listener.

let cells = document.querySelectorAll('.cell');

let temp = 0;
function clicker (x) {
  temp += 1;
  console.log('clicked',x.target.classList[1],temp);
  x.target.style.backgroundColor = 'red';
  if (temp === 3) {
    cells.forEach(c => c.removeEventListener('click', (el) => clicker(el)));
  }
  return;
}

cells.forEach(c => c.addEventListener('click', (el) => clicker(el)));
.main {
  display: grid;
  grid-template-columns: repeat(3,90px);
  grid-template-rows: repeat(2, 90px);
  row-gap: 5px;
  column-gap: 5px;
}

.cell {
  width: 90px;
  height: 90px;
  background-color: blue;
}
<div class="main">
  <div class = "cell fir"></div>
  <div class = "cell sec"></div>
  <div class = "cell thi"></div>
  <div class = "cell fou"></div>
  <div class = "cell fif"></div>
  <div class = "cell six"></div>
</div>

1 Answers

The function passed to removeEventListener has to be the same as the one passed to addEventListener. Since you're using an anonymous function in each place, they won't be the same functions.

Just use the name of the function rather than an anonymous function that calls it.

let cells = document.querySelectorAll('.cell');

let temp = 0;
function clicker (x) {
  temp += 1;
  console.log('clicked', temp);
  if (temp === 3) {
    cells.forEach(c => c.removeEventListener('click', clicker));
  }
  return;
}

cells.forEach(c => c.addEventListener('click', clicker));
.main {
  display: grid;
  grid-template-columns: repeat(3,90px);
  grid-template-rows: repeat(2, 90px);
  row-gap: 5px;
  column-gap: 5px;
}

.cell {
  width: 90px;
  height: 90px;
  background-color: blue;
}
<div class="main">
  <div class = "cell fir"></div>
  <div class = "cell sec"></div>
  <div class = "cell thi"></div>
  <div class = "cell fou"></div>
  <div class = "cell fif"></div>
  <div class = "cell six"></div>
</div>

Related