Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding event handler to newly created element

Tags:

jquery

dom

I'm trying to add new element to ordered list with link for it's removal:

$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

but this is not working:

$('a[href^="#remove"]').on('click', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

Any idea why?

like image 304
user1588241 Avatar asked Aug 09 '12 17:08

user1588241


People also ask

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

If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. 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 .

How can you assign event handler to some HTML element?

The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget. removeEventListener ).

How do I add an event listener to just once?

We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.


1 Answers

Wrap up the new element in jQuery tags and apply the event handler at that time. This is a cleaner and more efficient approach than using somewhat complicated jQuery selectors to assign the event handler after the element has already been inserted into the DOM:

//this line will create your element in memory, but not insert it to the DOM
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

//you can apply jQuery style event handlers at this point
newElmt.on('click',function(e) {

    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

//insert the element as you were before
$('#list ol').append(newElmt);
like image 107
Elliot B. Avatar answered Oct 20 '22 08:10

Elliot B.