Add Event Listener on Elements Created Dynamically

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

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>

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

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

Adding event listeners to dynamically added list elements

The added items are div tag elements. But the original items are i tag elements. The event.target.tagName === "I" test will only match the i tags, not the div tags.

Update the added items code (in both addListItemOnClick and addListItemOnPress):

document.createElement("div")

to be:

document.createElement("i")

add event listener to the dynamically generated elements captured from API using Javascript

Each button is already an element object and so you can use addEventListener directly on the element.

async function overViewMaker() {
const response = await fetch(api_url_overview.concat(api_key));
let data = await response.json();
data = data.results.lists;

// moved book_div out of for loop so it doesn't need to be re-queried for every book
var book_div = document.getElementById("book_list");

data.forEach((book) => {
let mybook = book.books;
mybook.forEach((eachbook) => {
var liTag = document.createElement("li");
var aTag = document.createElement("button");

var inpuHidden = document.createElement("input");
inpuHidden.setAttribute("type", "hidden");
inpuHidden.value = eachbook.title;
aTag.appendChild(inpuHidden);

aTag.addEventListener("click", (ev) => {
// you don't need to get book title from the hidden input element since it is in the scope
// inputHidden.value is also accessible from inside of here
const title = eachBook.title;
console.log(title);
});

liTag.appendChild(aTag);
book_div.appendChild(liTag);
});
});


Related Topics



Leave a reply



Submit