1

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?

1
  • Be sure to correct your mismatched tags. You're opening with a <span> and closing with a </div>. Commented Oct 14, 2010 at 13:11

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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 - Perhaps a simple CSS issue, where some invisible element overlays the new one? Hard to say.
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 :/
0

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.

1 Comment

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 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.