1

I'm kind of a noob in jquery, so i'm sorry if the question is a little obvious.

I wondered how should I handle an element which is created using the .html() jquery method, so there is no way to handle it after $(document).ready. Is there anyway to create the handler when the element is created or something?

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78

2 Answers2

4

Simple as that:

$('#containerId').on('eventType', 'childSelector', handler);

Always bind the delegate event to the closest static element of the dynamic elements.

If you want to understand how this magic happens, read the on docs

gdoron
  • 147,333
  • 58
  • 291
  • 367
0

For an example:

$("#mydiv").html("<span>Content</span>");
$("#mydiv span").css("background-color","blue");

so, call it after you set the .html().

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
  • You are absolutely right! but he's asking about **handlers**... like `on` \ `delegate` \ `live` – gdoron Mar 25 '12 at 22:16
  • Ok but I think he meant this by "handling" the element. $("#mydiv") is a "handler" to an element too. – Taha Paksu Mar 25 '12 at 22:22
  • 1
    And now I've read the title and saw the "event" word. :) Yea you're right. Your answer and mine should be written in one answer. – Taha Paksu Mar 25 '12 at 22:23
  • the problem was that the html string was not created at the same time as the document, but following an ajax request triggered after the document was loaded, so for some reason i couldn't get the handler for that on the .success of that request, I don't know why. – Tomas Raies Mar 25 '12 at 22:31