jQuery click event for dynamically created elements:

After scratching my head for 2-3 hours(before searching it on the internet) on this problem, i got to know the reason why this(.click()) doesn't work on dynamically created elements.

If you want to click on any  element(button/span/div/textbox/.....etc) using jQuery, we can do that by using  this code,

$('selector').click(function(){
//your code
})

This works fine if you have created that element already.

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

 Delegate():

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

Example:
$(document).delegate('selector', 'click', function()
{
//your code
});

ON():

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

Example:
$(document).on('click', 'selector', function()
{
// your code
});

In this way you can click on dynamically generated HTML elements..

For more posts on JQuery visit: JQuery

No comments:

Post a Comment