0

for some reason my "megaPixel" dynamically generated divs aren't responding when I click on them despite writing a function that selects all divs. all the other divs respond when clicked.

function init($input){
  for (i=1; i <= 20; i++){
  $('body').append('<div class="megaPixel" id="megaPixel_' + $input + '"></div>');
  $input = $input + 1;
  }
};

$('div').click(function(){
  $('.megaPixel').css('background-color', 'red');
});

init(1);
Alexander
  • 23,432
  • 11
  • 63
  • 73
modest_max
  • 41
  • 4

4 Answers4

1

That's because you are assigning the click listener before the divs are generated.

function init($input){
  for (i=1; i <= 20; i++){
  $('body').append('<div class="megaPixel" id="megaPixel_' + $input + '"></div>');
  $input = $input + 1;
 }
 $('div').click(function(){
    $('.megaPixel').css('background-color', 'red');
 });
};

init(1);

Try it like that.

caiocpricci2
  • 7,714
  • 10
  • 56
  • 88
  • wow i've been struggling with this since yesterday and within minutes i got 4 responses. for free. amazing. – modest_max Feb 24 '13 at 00:46
1

You could use this too:

$("body").on("click", "div.megaPixel", function(){
  $(this).css('background-color', 'red');
});
Dave L.
  • 9,595
  • 7
  • 43
  • 69
  • I think this may be the best suggestion so far. It won't matter when init was executed. You're binding your click handlers to body so they live there. Anytime you click on the page it will figure out if it applies to elements that are available at the time of the click. Nice work. – Will Klein Feb 24 '13 at 00:41
  • @WillKlein -- Haha, variations of this exact question are asked many times per day so it is an easy suggestion :) – Dave L. Feb 24 '13 at 00:45
0

I think you're looking for something like this.

$('div.megaPixel').on('click', function(){
  $(this).css('background-color', 'red');
});
Wing Lian
  • 2,387
  • 16
  • 14
0

Have you tried using $(document).on("click", "div.megaPixel", function() {} ); instead so that dynamically-added elements get included?

John Hornsby
  • 321
  • 1
  • 10