0

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??

2
Contributors
3
Replies
22
Views
1 Year
Discussion Span
Last Post by James_43
0

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?

1

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
});
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.