-2

How do I give a dynamically created element an event listener? In the example below, AFTER all this code execute the variable term_num increments up by one (term_num++) so every time the #abtn click event is called, a new div element "term_[term_num]" is created. How do I give each of these new divs a click event listener?

$( document ).ready(function() {
$( "#abtn" ).click(function( event ) {
        var newterm = '<div id=\'term_'+term_num+'\'>'+term+' </div>';
        var term = document.getElementById("term_input").value;
        $('#terms').after(newterm);
  • you'd have better to use a class instead and bind event using delegation – A. Wolff Jan 21 '14 at 19:37
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Kevin B Jan 21 '14 at 19:37
  • If you appreciate an answer, don't forget to "accept" the best one by clicking the checkmark to the left of the answer, underneath the voting arrows. This will also award you some reputation points! If a better answer comes along later, you can switch to that one. If you haven't taken the SO tour, check it out here: http://stackoverflow.com/tour – m59 Jan 24 '14 at 05:58

2 Answers2

2

You can just register it in advance with .on(): Live demo (click).

$(document).on('click', 'some-selector', function() {

});

or create the dom element newTerm before appending it and attach the function directly: Live demo (click).

var $newTerm = $(newTerm);

$newTerm.click(function() {

});

Since the selector you're adding to the element is a dynamic id, I'd recommend going with the second approach here. If you want to add a class to the generated elements so that you can delegate .on to them, use .on. It's more efficient.

m59
  • 43,214
  • 14
  • 119
  • 136
1

Add a class while creating them.

var newterm = '<div class="termsDiv" id=\'term_'+term_num+'\'>'+term+' </div>';

You need to use Event Delegation for dynamically create elemnts. You have to use .on() using delegated-events approach.

i.e.

$(document).on('event', 'selector', callback_function)

Example

$(document).on('click', '.termsDiv', function(){
    //Your code
    alert("clicked me"); 
});

In place of document you should use closest static container.

If you wish you can use Attribute Starts With Selector [name^="value"]

$(document).on('click', 'div[id^="term_"]', function(){
    //Your code
    alert("clicked me"); 
});

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Satpal
  • 132,252
  • 13
  • 159
  • 168