Here’s an example of my problem:
HTML
<p><a class="clickme" href="#">I would like to say:</a></p>
jQuery
$("a.clickme").click(function() {
$('p').append('<div><a href="#" id="say-hello">Hello</a></div>');
});
$("#say-hello").click(function(){
alert('test hello');
});
Here’s a fiddle with the example code:
http://jsfiddle.net/johnmorris/2UVYd/2/
The first click function fires just fine. But, the alert (or any other function) will not fire on the newly appended elements. I basically understand that the appended element didn’t exist on page load, so jQuery doesn’t “see” it… thus, the second click function not firing.
I’m just wondering if there’s a way around that. And, if so, what is it. I can’t seem to get this figured out.
You need to wait to assign the event until the element exists:
Notice that the
clickassignment for the newly created anchor is INSIDE the otherclickcallback.@Vega is using another technique called “delegation” where you assign the click for “say-hello” to the
pinstead of the anchor itself. When the anchor is clicked the event “bubbles” up through the DOM and is gets caught by the event listener on theptag. This works correctly, but this may not be the right time for delegation. Delegation is usually used when you have a collection of items inside of a common container (e.g. LIs in a UL) that all have to handle the same event. If you just have one “say-hello” then I would recommend not using delegation.
If you need to be able to click the button multiple times and have it inserted multiple times then delegation might be the right option (but you’ll need to stop using a hard-coded ID). Or… you could do it this way:
This code actually digs into the newly created elements and attaches the event before appending to the DOM. (Oh, and notice that I’m using a className rather than an id for “say-hello”.)