Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling events of HTML elements inserted by jQuery

Tags:

jquery

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"); });

like image 476
Kevin Pang Avatar asked Dec 22 '22 13:12

Kevin Pang


2 Answers

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.

like image 98
JakeJ Avatar answered Jan 02 '23 23:01

JakeJ


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).

like image 31
Eran Galperin Avatar answered Jan 02 '23 23:01

Eran Galperin