4

Possible Duplicate:
How can I detect when a new element has been added to the document in jquery?

I have a list of comments in a normal ul element. When loading the page I use something like (the system is based on templates)

<li id="someId">Some Content</li>
<script>doStuffWithLi('someId');</script>

So if the page is loaded and there are some li's, each one based on the template, there is this block for each li.

Now people can post a new comment and the template and the content is loaded into the page again - but this time the script is not executed. I guess js that is loaded after document ready in general is not executed, ones the document is loaded?

Unfortunately there is no jQuery function like $('li').live('ready', function() {});. I tried it with the livequery plugin like $('li').livequery(function() {//DO STUFF}); - But this didnt work as well. I cannot simply add a call to the creation of the element, because i can not influence the function adding the comment.

Is it possible to call a function as another li is added?

Community
  • 1
  • 1
KddC
  • 2,853
  • 2
  • 17
  • 19
  • 1) Why don't you hook into the function that adds the li in the first place? 2) http://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – Alexander Feder Feb 01 '13 at 12:25
  • @Alexander Feder 'I cannot simply add a call to the creation of the element, because i can not influence the function adding the comment.' – KddC Feb 01 '13 at 12:40

1 Answers1

3

You could use the event DOMSubtreeModified. Assign this event to the parent of your lis and check if the event gets fired if there is a new li. In this case you assign a new handler to that li.

$("#li_parent").bind("DOMSubtreeModified", function() {
    alert("possibly a li has been inserted");
    // do your magic here
});
Thariama
  • 50,002
  • 13
  • 138
  • 166