0

I'm using some existing code from jsfiddle, but it's using the deprecated .live function. When I change the code to use .on, it no longer works. Here is the jsfiddle: http://jsfiddle.net/DBfKz/

The script adds items to a "compare list". What I'm trying to do is click on the "x" next to one, to delete from the list.

This is the deprecated code:

$(".box a").live("click", function() {
    $(this).parent().remove();
    updateLinkAndCounter();
});

I convert it to this:

$(".box").on("click","a", function() {
    $(this).parent().remove();
    updateLinkAndCounter();
});

I change the version of jQuery to something newer, which supports .on

But now the script doesn't work. I've used .on before successfully, and I just don't know why it's not working here. Thanks for any and all help!

matwr
  • 1,548
  • 1
  • 13
  • 23

1 Answers1

0

The problem is that .box element is created after the dom is ready, so the element doesn't exist for it to attach an event to.

You need to add the event handler to an element that already exists.

http://jsfiddle.net/DBfKz/72/

I changed your event to look like:

$("#container").on("click", '.box a', function(e) {
    $(e.target).parent().remove();
    updateLinkAndCounter();
});

Also changed your version of jQuery from 1.4.4 to 1.8.3

It works the same way now.

Phill
  • 18,398
  • 7
  • 62
  • 102