Dean219 Dean219 - 5 months ago 7
Javascript Question

attach event to dynamic element

Hey im having a problem attaching an event to an element im dynamically generating. I would appreciate any advice on solving the issue im not sure whether its the method that im using to attach the event or whether its something else:

for (var i = 0; i < array.length; i++) {
itemlist=itemlist.concat('<pre'+' id="pres'+i+'"'+'>'+array[i]+'</pre>');

var name = '#pres'+i;
$( name ).click(function() {
alert( "Handler for .click() called." );
});
}


I also tried this method which i found on stack overflow however yielded no result :

var name = '#pres'+i;
$(name).on('click', function() {
alert( "Handler for .click() called." );
});


Whilst inspecting in chrome all of the elements exist with the correct ID, however the jquery event i have attached does not perform its alert. I have looked at some solutions however i do not want to attach the same function to all "" tags however attaching the same event to each of the ones in the loop would be acceptable.
Any help would be appreciated :)

Answer

Instead of generating unique id attributes, which makes the code needlessly more complex and can be a pain to maintain, you could instead use a single common class and attach a single delegated event handler to all the elements. Try this:

$('#myContainer').on('click', '.foo', function() {
    // handle the element click here...
    console.log($(this).text());
});

var html = '';
for (var i = 0; i < array.length; i++) { 
    html += '<pre class="foo">' + array[i] + '</pre>';
}
$('#myContainer').append(html);
Comments