Project Challenge 3: Deleting a Task from the To-Do List
Remove a task from the to-do list when the delete button corresponding to that task element is clicked.
We'll cover the following
Problem statement
In this challenge, the task is as follows:
- When the user clicks on one of the delete
button
elements nested within a task, remove the corresponding parent task element from the webpage.
This task is deceptively simple. The delete button element with the id
of delete
is dynamically generated upon the addition of a new task. The click event handler $("#delete").click()
will not work because jQuery only binds the event handlers to static elements that exist at the time of binding.
So, how do we add event handlers to dynamically generated elements? This is where the jQuery on()
method comes into play. Using the on()
method, we can assign the click event handler to the ancestor element present at the time of event binding. In the second argument of on()
, we specify the selector for the descendant elements of interest. The click event handler function is only executed if the specific descendant of that ancestor element is clicked.
We can bind a click event handler to a dynamically generated delete button
element like this:
$("div").on("click", "#delete", function(){
// code for event handler function
});
This event handler function is only triggered when a descendant of a div
element with id
of delete
is clicked.
Sample input
Click on the delete button corresponding to the “Complete assignment” task.
Sample output
The “Complete assignment” task is removed from the list along with all its child elements.
Coding exercise
The problem is designed for your practice, so you are encouraged to solve it on your own. If you are completely stuck, refer to the solution review in the next lesson for guidance.