0

I have a div that when pressed adds another div with the same class. But when I click on the dynamically added elements, nothing happens.

$('.container').on('click', function(){
  var newColumn = $('<li class="column"/>');
  var newState = $('<div class="container" unselectable="on">Nothing</div>');
  newState.appendTo(newColumn);
  newColumn.appendTo($('#canvas'));
});
.container{
  border:1px solid black;
  width:100px;
  height:40px;
  text-align:center;
  vertical-align:middle;
  line-height:40px;
  border-radius:10px;
  
  -webkit-user-select: none; /* Chrome/Safari */        
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

.column{
  list-style-type: none;
  display:inline;
  width:100px;
  float:left;
  margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="canvas">
  <li class="column">
    <div class="container" unselectable="on">
      works
    </div>
  </li>
</ul>

How can I make the click-event work for all the elements?

Johan Hjalmarsson
  • 3,433
  • 4
  • 39
  • 64

1 Answers1

5

Since the .container elements are created automatically by your script you have to use the event delegation on() to deal with fresh DOM :

$('body').on('click', '.container', function(){
     //Your code here
});

Hope this helps.


$(document).on('click', '.container', function(){
  var newColumn = $('<li class="column"/>');
  var newState = $('<div class="container" unselectable="on">Nothing</div>');
  newState.appendTo(newColumn);
  newColumn.appendTo($('#canvas'));
});
.container{
  border:1px solid black;
  width:100px;
  height:40px;
  text-align:center;
  vertical-align:middle;
  line-height:40px;
  border-radius:10px;
  
  -webkit-user-select: none; /* Chrome/Safari */        
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

.column{
  list-style-type: none;
  display:inline;
  width:100px;
  float:left;
  margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="canvas">
  <li class="column">
    <div class="container" unselectable="on">
      works
    </div>
  </li>
</ul>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36