A_funs
A_funs

Reputation: 1246

jquery does not select jquery added element

So I have a jquery function that does something when class 'ajaxsubnote' is clicked

$('.ajaxsubnote').click(function(){
     //do something....
})

But the user can add elements with class 'ajaxsubnote' dynamically via jquery. My problem is these dynamically added elements, when clicked, don't seem to call the above function, whereas the ones originally on the DOM do...

Any way around this?

Upvotes: 0

Views: 891

Answers (3)

jholloman
jholloman

Reputation: 1979

The difference between a bind/click event and a delegated on event is this very important.

When you use bind or a shortcut such as click, it binds the designated event to all elements matching the specific selector at that time. This selector is a snapshot in time and is not updated when new elements are added.

When you use event delegation you provide a static parent selector and then your dynamic element selector. Now when you click anywhere within the parent selector, jQuery checks to see if the target matches the parent selector. If the target matches the second selector then the event is triggered. This means that you can add and remove elements to the parent content section that match the criteria for the event triggering without having to bind events every time.

http://api.jquery.com/on/

So what you need is something like:

$(parentElement).on( "click", ".ajaxsubnode", function(){
     //do something....
});

Where the parentElement is as specific as possible while still being a parent of all possible ajaxsubnode classes.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You should use delegated event method to handle dynamic elements. See below,

// v--- replace document with closest parent container that exist in DOM
$(document).on('click', '.ajaxsubnote', function(){
     //do something....
})

For older versions use delegate,

// v--- replace document with closest parent container that exist in DOM
$(document).delegate('.ajaxsubnote', 'click', function(){
     //do something....
})

Upvotes: 2

Jan
Jan

Reputation: 5815

You need to use the on() function to delegate the click event

$("dynamicContainerElement").on("click", "dynamicallyAddedElement", 
     function () 
     { 
        /* Your code here */
     });

http://api.jquery.com/on/

Upvotes: 1

Related Questions