2

I am trying to create a list of divs. When the new layer button is clicked, there is a new div created with a unique ID. When I try to call on these dynamically added divs, there is no response. I am confused because the preexisting divs work.

<input type="submit" id="newLayer" value="New Layer">

 <div id="layersContainer" class="layerscontainer">
    <div class="layer" id="layer1">fadfa</div>
    <div class="layer" id="layer2">2</div>            
 </div>


var newLayerCounter = 2;
var layerID = "";
var layersArray = new Array();
var clickedElement = "";


function selectLayer(){

      $(clickedElement).css({"background-color":"yellow"});

    }

$('#layersContainer div').on("click", function(){

    clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();

});

$('#newLayer').on("click", function(){

    newLayerCounter = newLayerCounter + 1;
    layerID = "#layer"+ newLayerCounter;

    $('<div/>', {
    id: "layer"+ newLayerCounter,
    class: "layer"
   }).appendTo('#layersContainer');

    $(layerID).text('hey');

})

Here is a link to a working JSfiddle

http://jsfiddle.net/Q3dSp/24/

user1551909
  • 461
  • 1
  • 4
  • 9

4 Answers4

3

Change your

$('#layersContainer div').on("click", function(){

to

$(document).on("click", '#layersContainer div', function () {
    clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();
});

It is known as delegated event.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 1
    Why what he did isn't working though ? Is it not jQuery event delegation? (the way he did it) – Joel Blum Feb 22 '13 at 17:46
  • @Joel_Blum Ah! It's the second question today. Forgot the name yet again. Older question: [When clicked insert text into ul li](http://stackoverflow.com/a/15027042/1190388) – hjpotter92 Feb 22 '13 at 17:49
  • And it's even a duplicate of http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand. I encourage everyone who can to close such a question as duplicate of the linked one. – Felix Kling Feb 22 '13 at 17:53
0

Try with $('#layersContainer').on("click", "div", function(){ (...) });

http://jsfiddle.net/3hqfn/1/

Vincent Simard
  • 524
  • 3
  • 8
0

change :

$('#layersContainer div').on("click", function(){

with this:

$('#layersContainer').on("click", "div", function(){
Oden
  • 756
  • 8
  • 21
0

Try with this one:

 $('#layersContainer').on("click", 'div', function(){
clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();
 });

In this situation you need a event delegation to existing closest parent when dom was ready.

Jai
  • 74,255
  • 12
  • 74
  • 103