View Full Version : jquery click command not working on dynamically added html

Apr 12th, 2009, 11:00 AM

i am dynamically adding html to my page using the .html(...) function which is triggered based on some user action.

i have also defined a click function specific to some id tags that is in the dynamic html. when i generate the dynamic html and call the click function, nothing happens (aka, the click function is not getting called...) what could be the problem?

i have attached the code below:

following html code called upon a user action, which adds a button on the page with id = addTask:

.html("<input name='add' type='button' value='Add' id='addTask'>")

when the user clicks on this button, the following function should be called, but it ISNT...and this is the issue:

$('#addTask').click(function() {

when i click the add button, i don't get an alert...

Apr 14th, 2009, 05:49 AM
Well I've got two questions, are you using the same ID for two elements? Because you say you dynamically insert the data, so could it be inserted twice? If so, use a class. The second is do you add the event listener before or after? If it's before, you need to place it after.

If you are using a class, and it is being inserted multiple times, you should look into using the live function which works similar to binding. It'll allow you to insert dynamic data without having to bind it all the time.

Apr 14th, 2009, 04:12 PM
This is because you are binding your click event to the element that is not yet created. To overcome this problem use .live() function available in jQuery 1.3 as Iszak suggested.

If you are using jQuery 1.2 and can't change it read this article on how to bind events to newly created DOM elements (http://jquery-howto.blogspot.com/2008/12/how-to-bind-events-to-ajax-loaded.html).

Jan 25th, 2011, 06:14 AM
$('#divid').live('click', function() {

Jul 1st, 2013, 10:43 AM
Source : http://coding-issues.blogspot.in/2013/06/javascript-jQuery-click-not-working-for-dynamically-created-items.html

if you created your elements dynamically(using javascript), then this code doesn't work.
Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

Earlier we have .live() function

$('selector').live('click', function()
//your code

but .live() is deprecated.This can be replaced by other functions.


Using delegate() function you can click on dynamically generated HTML elements.


$(document).delegate('selector', 'click', function()
//your code


Using on() function you can click on dynamically generated HTML elements.


$(document).on('click', 'selector', function()
// your code