We have to add click event to an existing element. We can not add event to DOM elements dynamically created. If we want to add event to them, we should bind event to an existed element using “.on” or “delegate”
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 we are dynamically creating our elements using javascript, it doesn’t work.
For this we 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
});