0

I am creating various objects with my plugin, then I append more objects to them, and so when i do that i need to select those fresh objects.

I have made very simple jsfiddle here: http://jsfiddle.net/6zBGj/2/

And now as you can see I append item div to the $container and so when user clicks on item i want to do something, but i can't find a way to select it.

Please keep in mind that this is a plugin, and i do not want to select it like this: $(".container .item") I need to work with each individual object separately.

P.S don't mind messy code it's just an example.

Linas
  • 4,380
  • 17
  • 69
  • 117

3 Answers3

1

If you create your element in memory first, attach the event handler there and then you can append that variable to the parent. Like this:

var $item = $("<div class='item'></div>").click(function() {
    alert("Foo");
});
$container.append($item);

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

The divs don't exist yet, so you can't attach listeners to them. What you can do is delegate the event listening for all divs inside the container to the container itself:

$container.on("click", "div", function(){
   $(".event").append("clicked! <br />");
});

Here is a demonstration: http://jsfiddle.net/6zBGj/4/

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

If you know what will be added to the container then you can do this - http://jsfiddle.net/aYgvm/

All i did was change:

$("div", $container).live("click", function(){
   $(".event").append("clicked! <br />"); 
});

to:

$($container).on('click','div', function(){
   $(".event").append("clicked! <br />"); 
});

You should also avoid using live() - Jquery live() vs delegate()

Community
  • 1
  • 1
boz
  • 4,891
  • 5
  • 41
  • 68