Hi all,

I have a text box. When users press enter, it triggers the submit function:

commentContent.keydown(function(e){
    if(commentContent.is(":focus") && (e.keyCode || e.which) == 13 && !e.shiftKey)
    {
        e.preventDefault();
        commentForm.submit();
    }
});

This then prepends the content of the text box into the HTML.

commentsHere.prepend(commentData);

However, when I search for this new element by id and class, it doesn't register. Do I need to tell JS to refresh the DOM so I can find it? I have read some discussions about using .on(), does that mean I need to register an event to listen for prepend events??

I realise this isn't about the DOM updating. I use the following functions to pull up the elements and process their click events:

$('.like').each(function(i, obj){

    $(this).click(function(e){

        var element = $(this);

        //stuff
        })
});

Obviously since the .each() function loads with the page, it doesn't take into account anything I add dynamically... How can I add the objects I add to the DOM dynamically?

Member Avatar for diafol

You may need to use the .on trick for delegated events.

http://api.jquery.com/on/

Simply, you have a container (in the original HTML) and you add stuff to it. If you reference the container, it acts as a magic box that allows you to run functions on items that don't exist yet. Not sure if I explained myself properly.

example:

$( "#container" ).on( "click", ".item", function() {
  //do whatever
});

Yes. Not only did that fix it, but got rid of the .each() function :) Thank you very much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.