views:

137

answers:

3

I want to use jQuery to create a new div on the page when a certain link's click event is activated. I know this part will be fine. The part I am concerned about is this: if inside of the newly created div is another link, will I then be able to use jQuery to capture the click event of this new link? I.e. will the javascript be able to capture click events of the new html element that was 'dynamically' inserted using jQuery? If not, how can I mimic this functionality?

Thanks

+2  A: 

Yes, there's a feature in the new jQuery called 'live'. You may need to access 'livequery' as well, depending on what you need to do.

live: http://docs.jquery.com/Events/live#typefn

livequery: http://docs.jquery.com/Plugins/livequery

Good luck!

David
Yes! thank you! I'm so glad they have this feature...
You're welcome! FYI I use livequery for what I needed (as opposed to live), I think its a well used plugin.
David
+2  A: 

David's right - live is pretty cool and I use it often. There are some events that cannot use live - so for the sake of completeness, you can also wire up new events as you modify the DOM. For example:

$("#some_link").click(function() { 
  $("great_selector").html("<a id='radtimes' href='/radtimes'>rad times</a>");
  $("#radtimes").click(function() {
    alert('more rad things happened!');  
  }); 
});
Andy Gaskell
I think with "livequery" most of those things should be handled (for practical purposes), but that's cool.
David
A: 

I see you've got an answer, but here is some sample code that creates a new link and binds a function to its click event in one go. Modify as necessary for nested elements. The use of chained function calls here is to avoid potential problems with quote escaping if HTML in a string is used. Oh, and the return false is good to have at the end of a click handler as it prevents the link from activating.

$('body').append($('<a>').attr('href', '#').text('Foo').click(function() {
    alert('Foo!');
    return false;
}));
Jason S
I think he wanted recursive adding, so that might not suffice.
David