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"); });
The problem that you have is that when you have the code $('#Element').click(function(){...});
, it will only ever run the code on elements that were present when that code was ran in the first place, if you are using the latest version of jQuery, you should use this code to make it work:
//This makes sure that all the elements are ready to receive jQuery bindings
$(document).ready(function(){
//The .on function will attach the event to all current
// elements that match the selector and all future elements
// that will match the selector
$(document).on('[EVENT]', '[SELECTOR]', function(){
//Do Stuff
});
});
This code along with any other jQuery code that attaches to elements (using the .on() function or not) should all be withing a document.ready as above.
This will run the event (In your case, [EVENT]
will be click
) for any element now, and in the future that match the [SELECTOR]
(In your case, #id
)
JSFiddle Example: http://jsfiddle.net/DhWmP/
Source(s): http://api.jquery.com/on/ & Experience with inserting elements on a page that need functions.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With