0

I have a (probably) very easy problem to fix, but I can't figure out what's wrong. I try to run .click() jquery but it does not trigger. I think it's because the actual DOM items get created dynamically with javascript (does it matter?).

the dynamically created content is:

<div class="rPics">
    <div class="class">
        <canvas id="canSSJ01" class="thumbCan" width="600" height="720"></canvas>
        <p class="cDID hidden">SSJ01</p>
    </div>
    <div class="class">
        <canvas id="canSSJ02" class="thumbCan" width="600" height="720"></canvas>
        <p class="cDID hidden">SSJ02</p>
    </div>
</div>

Javascript:

$('.class').click(function(){
  globalJID = $(this).children(".cDID").text();
  console.debug("clicked thCC: "+globalJID);
});

Now when I check chrome, it does not trigger the .click function at all :(

what am i doing wrong?

Tomasz Golinski
  • 743
  • 5
  • 25

3 Answers3

2

If the elements are created dynamically, then you want to use

$( document ).on( 'click', '.class', function () {

Also you might want to rethink having the class name being class.

Refer here for the documentation. Refer here for a similar question.

Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94
  • the name of class was changed for easier read in here actual class name is thumbCanCon.. but I thought it would be easier to see what I'm talking about when the class is short and clear – Tomasz Golinski Jan 12 '14 at 08:04
  • @TomaszGolinski - OK, glad to hear that the name is not class. – acarlon Jan 12 '14 at 08:30
2

You need to use .on() method and learn event delegation, for dynamically created elements. Bind event with nearest static container

$(document).on('click', '.class', function(){
  globalJID = $(this).children(".cDID").text();
  console.debug("clicked thCC: "+globalJID);
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

As the items are created dynamically, you can use event delegation with jquery .on() method:

$(document).on('click', '.class', function (){   //Here use `on`
  globalJID = $(this).children(".cDID").text();
  console.debug("clicked thCC: "+globalJID);
});

If you're with an oldie jquery version, you can accomplish the same with live

 $(document).live('click', function (){ 
halfer
  • 19,824
  • 17
  • 99
  • 186
Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • Hi Edgar. Your answers are great, but can I request that you don't add thanks or "hope this helps" to every one? They will [generally be edited out](http://meta.stackexchange.com/questions/34464/questions-with-lots-of-thank-you-answers) anyway. – halfer Jan 12 '14 at 08:45