tags:

views:

34

answers:

2

I like to create jquery elements in variables and place them where needed.

var $someElement = $("<span class='someclass'>something</span>").css("cursor", "pointer");
$("body").append($someElement)

for now everything is working. But if i try to bind a event to this element, the event does not get triggered:

var $someElement = $("<span class='someclass'>something</span>").css("cursor", "pointer").click(function(){ alert("yeah") });
$("body").append($someElement)

but if i append the element and the find the span by its class it works.

Why is this and how should i handle events on elements that are created but not yet apended?

A: 

Establish a delegated event handler for your elements with the .delegate() function.

$('#yourContainer').delegate('.someclass', 'click', function() { ... });

Then any of those "someclass" elements you drop inside "yourContainer" (which could be the <body> of course) will have its "click" events handled by that function.

Pointy
Thanks @patrick dw!! I need a cheat sheet in front of me for just about every API I use - you can imagine how painful it is to use Java all day :-)
Pointy
Pointy - Not a problem. :o)
patrick dw
+1  A: 

Your code should work just fine:

Example: http://jsfiddle.net/HHNaF/ (your code, copied and pasted)

One alternative you have available to you is to use .live() to assign the handler:

$('span.someclass').live('click',function() {
   // do whatever
});

But still, your code should work. I'm guessing there's something else going on that is preventing the handler from triggering.


EDIT: Just noticed that your tags are mismatched. You start with <span> and end with </div>. Be sure to correct that. :o)

patrick dw
sorry for the example, in my script its right ;P but it does not work for some reason. I have to find out why. Thank you for your help
meo
@meo - Perhaps a simple CSS issue, where some invisible element overlays the new one? Hard to say.
patrick dw
no because the "cursor : pointer" works. But i think its a JS problem, i have to integrade my script in a system that already uses a lot of uncommented JS :/
meo