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?
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 .
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.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
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 });
$(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
.
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