Okay, I have a todo app that i'm creating with JS. I have an addtodo function which adds the items when clicked and also runs a for loop for each of these list elements, which have a classname of 'list', to style them. The thing is, the for loop runs everytime I add the todo list which I think add's multiple event listeners to the already existing items with the same function. I'm trying to toggle a class for priority function when clicking on a paragraph with classname of 'thevalue'. My problem is the event listener runs multiple times and cancels the toggle. The first item runs once, which is correct, and the second item runs, twice, and the third runs three times as follow. I will attach the code below. It would be of great help if you could solve my issue.
var theListPara = document.getElementsByClassName('thevalue');
if (theListPara[0]) {
for (var i = 0; i < theListPara.length; i++) {
theListPara[i].addEventListener("click", changePriority);
}
function changePriority() {
var theClassName = this.parentElement.classList.contains('normal');
if (theClassName) {
this.parentElement.classList.toggle('high');
}
}
}
This whole line of code runs whenever the add todo is clicked.
Event Delegation is the way forward. Its philosophy is very simple, event listener is attached to static-parent-element then it analyses the bubbled
event.target
. if match is found then the desired operation can be performed.Element.matches() API can also used to validate element matches a given selector.