meo
meo

Reputation: 31249

binding events on jquery created DOM elements

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?

Upvotes: 1

Views: 1054

Answers (2)

user113716
user113716

Reputation: 322492

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)

Upvotes: 1

Pointy
Pointy

Reputation: 413737

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.

Upvotes: 0

Related Questions