13/14: Why must use `on` handler


#1

I think this code will work, as I understand in my mind that when I click on a element has item class it will remove the element, so why it not work and we must use on handler.

$('.item').click(function() {
    $(this).remove();
});

thanks for reading!


#2

Hi Markstevenshpvn,

With that code, it queries the document for all elements with the item class. The problem is, there are no items on page load, because they only get added after you submit the form.

By using a $(document).on(...); event handler however, it listens for clicks anywhere on the page, then checks if the click landed on something with the item class. This way, it can listen for clicks on elements that don't exist when the page initially loads.

Make sense? :slight_smile:


#3

A post was split to a new topic: Why will it not work?


#4

hey that was actually a pretty good explanation to clear my doubts. thanks


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.