Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding event listeners to dynamically added elements using jQuery [duplicate]

Tags:

jquery

events

So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.

Is there any way to bypass this, so you don't have to execute a whole extra block of code?

like image 406
Wiz Avatar asked Aug 22 '12 01:08

Wiz


People also ask

How do you add an event listener after an element was created dynamically?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .

Can you add multiple event listeners to an element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.


2 Answers

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {   //do something }); 
like image 147
Jack Avatar answered Oct 14 '22 09:10

Jack


$(document).on('click', 'selector', handler); 

Where click is an event name, and handler is an event handler, like reference to a function or anonymous function function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

like image 27
zerkms Avatar answered Oct 14 '22 08:10

zerkms