When I click the buttons, I see the console message showing that I've clicked them. When I uncheck the checkbox and then click the buttons, I expect no console messages but I still see them. Why doesn't the removeEventListener remove the event listener?
const buttons = document.querySelectorAll('ul li button');
function initialize() {
for (let i = 0; i < buttons.length; i++) {
function doSomething() {
console.log(`You clicked on ${buttons[i].textContent}`);
}
if (document.querySelector('#mode').checked) {
buttons[i].addEventListener('click', doSomething);
} else {
buttons[i].removeEventListener('click', doSomething);
}
}
}
document.querySelector('#mode').addEventListener('click', initialize);
initialize();
<input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
<li><button>One</button>
<li><button>Two</button>
<li><button>Three</button>
<li><button>Four</button>
I can't define doSomething outside of the for loop because I need i to do other stuff (not shown here for the sake of simplicity). I do need different handlers for each index.