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>