tags:

views:

708

answers:

4

I currently have an anchor tag that, when clicked, appends another anchor tag to the DOM. This is all done via jQuery. I know what the "id" attribute of the anchor tag to be added will be. However, when I try the following code, it fails to handle the newly added anchor tag's click event:

$("#id").click(function() { alert("test"); });

+2  A: 

Are you attaching the click event before the element is added to the DOM? in that case it won't work. You need to either attach the event after the element is inserted to the DOM or add a listener that intercepts DOM changes and adds the event after the DOM is updated (similar to what the livequery plug-in does).

Eran Galperin
I fixed the typo. In the code I did have the selector.
Kevin Pang
+1  A: 

Is it possible that the code you pasted here is being executed before the new DOM node is actually available? If so, you can try using the .ready() method and attach your click after the fact.

$("#id").ready(function() {
    $("#id").click(function() { alert("test"); }
});

EDIT: I am somewhat new to jQuery myself, and I thought that the .ready() method was usable by more than just the document object. If this turns out to not be true, it looks like there is a jQuery plugin, jQuery.Listen, that does something similar:

// Listen to clicks, even for newly added instances of #id.
jQuery.listen( 'click', '#id', function(){ alert("test"); });

Something like this would be nice if you can use classes for your dynamically added anchors.

// Listen to clicks for anything with the class "dynamicAnchors", even newly
// added anchors.
jQuery.listen( 'click', '.dynamicAnchors', function(){ alert("test"); });
Beau Simensen
A: 

As the others have said, you can't attach event handlers to elements that don't exist yet. So if your code snippet is in the doc ready, it won't work.

Just put the $("#id").click(function() { alert("test"); }); in the jQuery code that adds the anchor.

Mike Scott
A: 

Event Delegation

If you upgrade to the new 1.3 beta they have a live() method that will handle delegated events. If you cant upgrade you can easily roll event delegation yourself. Explained in my response here

redsquare