Attach event to dynamic elements in javascript
This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
jquery makes it easier:
$(document).on('click','#btnPrepend',function(){//do something})
Here is an article about event delegation event delegation article
Attach event to dynamically created elements in javascript
You should notice that you get updateDelete
before you create another dynamic
part. You could log updateDelete
and you will find that it nerver changed.
So you could bind a click listener to higher level element, like this:
put.addEventListener('click', function (e) {
if (e.target.classList.contains('active-update')) {
console.log('click')
}
})
Or add click listener to every button you created dynamically.
Event binding on dynamically created elements?
As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:
This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
Attach runtime event to dynamic elements in javascript?
All you need to do is to add a () =>
. You need to pass a function as a second parameter to addEventListener
, and in your case your function is executed immediately.
btn.addEventListener('click', () => result(
'first value',
'second value'
));
Add click event on a dynamically created element in Javascript
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
https://jsfiddle.net/yu1kchLf/
Attach scroll event handler to an dynamically created element
Thanks to this answer I was able to do it:
function addPostponedEventListener(selector, eventName, handler)
{
let interval = setInterval(() =>
{
let el = document.querySelector(selector);
if (el)
{
el.addEventListener(eventName, handler);
clearInterval(interval);
}
}, 100);
}
add event listener on elements created dynamically
It sounds like you need to pursue a delegation strategy without falling back to a library. I've posted some sample code in a Fiddle here: http://jsfiddle.net/founddrama/ggMUn/
The gist of it is to use the target
on the event
object to look for the elements you're interested in, and respond accordingly. Something like:
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.tagName.toLowerCase() === 'li') {
// do your action on your 'li' or whatever it is you're listening for
}
});
CAVEATS! The example Fiddle only includes code for the standards-compliant browsers (i.e., IE9+, and pretty much every version of everyone else) If you need to support "old IE's" attachEvent
, then you'll want to also provide your own custom wrapper around the proper native functions. (There are lots of good discussions out there about this; I like the solution Nicholas Zakas provides in his book Professional JavaScript for Web Developers.)
Related Topics
Calculate Text Width With JavaScript
How to Disable Scrolling Temporarily
JavaScript: Do I Need to Put This.Var For Every Variable in an Object
How to Do String Interpolation in JavaScript
Looping Through Array and Removing Items, Without Breaking For Loop
Accessing the Web Page'S Http Headers in JavaScript
How to Get Image Size (Height & Width) Using JavaScript
Difference Between a Function Call and Function Reference
Client on Node.Js: Uncaught Referenceerror: Require Is Not Defined
How to Update Nested State Properties in React
Benefits of Using 'Object.Create' For Inheritance
Window.Close and Self.Close Do Not Close the Window in Chrome
Is It an Anti-Pattern to Use Async/Await Inside of a New Promise() Constructor
_Proto_ Vs. Prototype in JavaScript
Deleting Array Elements in JavaScript - Delete VS Splice