0

After the user creates a div with a button click I'd like to be able to click on that div and change its color. I'm wondering why this is not possible. It works if the div is hard coded in but not after it is dynamically created. Also, how do I make it work?

$("#addDiv").click(function() {
    var div = '<div id="clickMe" style="width:200px; height:200px; background:blue;"></div>';
    $("#container").html(div);
});

$("#clickMe").click(function() {
    $(this).css("background", "red");   
});
kybak
  • 820
  • 3
  • 13
  • 28
  • `$(document).on('click', '#clickMe', function(e){ ... })` is your friend, as googling for "javascript event delegation" is. – moonwave99 Jan 28 '16 at 18:27

2 Answers2

0

You need event delegation for dynamically generated element like following.

$('body').on('click', '#clickMe', function() {
    $(this).css("background", "red");   
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

No problem. Just create listener right on the created element. Something like this:

$("#addDiv").click(function() {
    var $div = $('<div/>', {
        id: 'clickMe',
        width: 200,
        height: 200,
      })
      .css('background', 'blue')
      .click(function() {
          $(this).css("background", "red");   
      });
    $("#container").html($div);
});

JSFiddle

Igor Adamenko
  • 861
  • 1
  • 8
  • 20