onclick event with jQuery for a dynamically created div

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

onclick event with jQuery for a dynamically created div

I am using a jQuery script that adds dynamically a Div in the DOM. I am trying to ad onclick event for this div.
HTML:

Code: Select all

<div class="ui23"><span>Track1</span></div>
After the Div is added dynamically in the DOM it looks like this

Code: Select all

<div class="ui23">
<div class="sm2_23ui"><span class="sm2_360btn sm2-360btn-default">Button</span></div>
<span>Track1</span>
</div>
My jQuery code to register onclick to ".sm2_23ui" element:

Code: Select all

$('.sm2_23ui').live(click,function(){
  alert("Playing");
});
But it doesn't work.
Does someone know how to register onclick event for a dynamically created html element?

Admin Posts: 805
The live() method for registering events in jQuery is deprecated. Use instead the on() method.
This is called event "delegation".

Code: Select all

$(document).on('click', '.sm2_23ui', function(){
  alert("Playing");
});