Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: adding event handler to just created element

Tags:

jquery

I have a statement adding a new div:

$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');

But I'd like to not only create element but also to assign on('click') action to it. Of course I could add generated id and then acces to created element by this id, but I feel that there is more beautiful solution.

Is it?

like image 771
Roman Matveev Avatar asked May 24 '13 07:05

Roman Matveev


2 Answers

You don't need to add an id and then ask jQuery to parse a selector to find the element. You can directly do this :

$('#dates').append(
    $('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>')
    .click(function(){
      // handle click
    })
);
like image 132
Denys Séguret Avatar answered Oct 26 '22 10:10

Denys Séguret


you can use jquery ON.. and also you can use class selector instead of id :) like $(".classname")

$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');

$('#dates').on('click','.'+classname, function(){
alert("on div click");
});

$('#dates').on('click','.month_selector', function(){
alert("on SPAN click");
});
like image 20
rahul maindargi Avatar answered Oct 26 '22 10:10

rahul maindargi