My CodePen
So when I click the delete and complete buttons it runs these functions
function deleteListItem(){
alert("Item was deleted");
}
function completeListItem(){
alert("This item was completed");
}
for both buttons. I want to know how I can use event delegation to separate these functions, that way whenever I click the complete button it isn't running both functions.
In your javascript, when you declare deleteButton
and completeButton
they are both assigned the same element, the ul
. That element contains the entire list. That is not what you want, you want to handle clicks on the buttons. deleteButton
should be assigned to your delete button element and your completeButton
to your complete button element. To do this, simply use the ID of the buttons you want instead of the ID of the UL.
In you code, change this:
var deleteButton = document.getElementById("todo");
deleteButton.addEventListener("click", deleteListItem);
var completeButton = document.getElementById("todo");
completeButton.addEventListener("click", completeListItem);
To this:
var deleteButton = document.getElementById("Remove");
deleteButton.addEventListener("click", deleteListItem);
var completeButton = document.getElementById("Complete");
completeButton.addEventListener("click", completeListItem);
EDIT:
Since your buttons are not unique you should not use an id to add the event listener. You should use a class and assign the event listener to all the elements with the class by looping threw them. In your html add a class attribute to your buttons like this: <button class="Remove"><i class="fa fa-trash" aria-hidden="true"></i></button>
. Then handle the events this way:
var deleteButtons = document.getElementsByClassName("Remove");
for (var i = 0; i < deleteButtons.length; i++) {
deleteButtons[i].addEventListener('click', deleteListItem, false);
}
var completeButton = document.getElementsByClassName("Complete");
for (var i = 0; i < completeButton.length; i++) {
completeButton[i].addEventListener('click', completeListItem, false);
}