Event Binding on Dynamically Created Elements

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

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

Bind custom event to dynamic created elements

According to my understanding, .oneordoubleclick is not an Event, just like .footable or .tooltip. Therefore, you cannot put it in $(document).on("oneordoubleclick","#test", ...)

Here's my solution, with the aid of the plugin source code:

// Custom functions
let singleClick = function () { // your function when is single click
alert('you have clicked this node.');
}

let doubleClick = function () { // your function when is double click
alert('you have double clicked this node.');
}

// Necessary to differentiate is single or double click
let timer,
do_click = function (e, fx) {
clearTimeout(timer);
timer = setTimeout(function () {
fx();
}, 400); // if there is no another click between 0.4s, then it is single click
},
do_dblclick = function (e, fx) {
clearTimeout(timer); // the single click function will not be called
fx();
};

// Listener
$(document) .on("click", "#test", function (e) { do_click(e, singleClick) })
.on("dblclick", "#test", function (e) { do_dblclick(e, doubleClick) })

Correct me if I'm wrong.

Add event binding to dynamically created components

Using ComponentRef.instance allows you to access the component instance and with this you can subscribe to the EventEmitter:

newComponent.instance.onDataRateChange.subscribe(evt => this.result = evt);

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

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

So instead of...

$(".myclass").click( function() {
// do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
// do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

Event Binding on Dynamically Created Line Items with Parameter

Your code is supposed to be working... The only reason I see to make it non-working is value.ConnectionId maybe is a string.

So I suggest you to use templating literals, so the quote issues would be easier to manage than a string concatenation.

Try this:

$('#notiContent').append($(`<li onclick="startUserChat('${value.ConnectionId}')">New contact : ${value.UserName} (${value.ConnectionId})</li>`));

Notice there are some quotes around the passed argument ${value.ConnectionId}.



Related Topics



Leave a reply



Submit