Using jquery to create a div using a button and then capture a new button click event?

I want to use jQuery to create a new div on the page when a specific click event is fired. I know this part will be fine. The part I'm worried about is this: if there is another link inside the newly created div, can I use jQuery to capture the click event of that new link? That is, will javascript be able to capture the click events of a new html element that has been "dynamically" inserted using jQuery? If not, how can I mimic this functionality?

thank

+2


source to share


3 answers


Yes, there is a function in the new jQuery called "live". You may also need access to "livequery", depending on what you need to do.

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



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

Good luck!

+2


source


David is right - life is pretty cool and I use it a lot. There are some events that cannot be used live - so for completeness, you can also wire in new events when the DOM changes. 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!');  
  }); 
});

      

+2


source


I can see you have an answer, but here is some sample code that creates a new link and binds a function to a click event in one go. Modify if necessary for nested items. The use of chained function calls here is to avoid potential quote evacuation issues if HTML inline is used. Oh, and it's return false

good to have a click handler at the end as it prevents the link from being activated.

$('body').append($('<a>').attr('href', '#').text('Foo').click(function() {
    alert('Foo!');
    return false;
}));

      

0


source







All Articles