Event listener, problem with the parameter in the function

Hello, I am working on a todo-list app and have a problem.

Inside a class, I have a method called addNewTask(), which adds a new task to the list and most important, create an icon, which when user click to, needs to call a method removeTask which will delete this task:

document.getElementById(deleteIcon.id).addEventListener("click", function(){

The problem is, that it doesn’t assign the value right in the moment, but when the user click the icon. So it always delete the last task. I need something like a self.removeTask(1), then self.removeTask(2)…

How can I solve this? I am sorry for a bad explanation, let me know if it’s really bad, I can try to explain it better.

I solved this issue by declaring the ‘x’ before the addEventListener method:
let x = this.lastTaskId;

and then just used ‘x’ as a parameter :smiley:

The event listener will automatically pass an event object into your event handler function (removeTask). This event object will allow you to determine which icon was clicked on and with that information you can determine which task to delete.

First thing you’ll want to do is call the addEventListener a little differently:

document.getElementById(deleteIcon.id).addEventListener("click", self.removeTask);

Notice how I am just passing the name of the function. That’s OK, because the event listener is going to automatically pass an event object into the removeTask function, which you will be able to use to determine which delete icon was clicked on.

In order to make this work, when you define the removeTask function you need to add the event object as an argument to the function, for example:

function removeTask(event) { ... }

Now you are set up to receive the event object. The event object allows you to determine which delete icon was clicked on by looking at the target property (you would access it through the object as event.target). Now you just need to figure out how you would associate each delete icon with its related task.

One way you could do this is to add a data attribute to the delete icon which holds the task ID you want to delete:


Then when the icon is clicked and the removeTask function is called, you can get the task ID from the event object:


That is definitely one way to solve it but it is probably not the optimal way. Right now you are adding an event listener on each individual delete icon. This is going to hurt performance as more icons are added to the page. The better way to do this is to use event delegation to handle the clicks on the delete icons. Basically, you add one click handler for all of the delete icons on an element that wraps the icons and then take advantage of the fact that the click event will bubble up to that element. But in order to do this you will need to use the approach I outlined above in which you inspect the event object to figure out which icon was clicked.

1 Like