2

I'm trying to build my first "serious" webpage. I have just started and I stuck on applying old event listeners on new div section. I would like to apply all old listeners on $(".novo").append("new div ..") I have tried to use on() functions but it doesn't seem to work. And also I have issues when adding new list. It adds to every present div. I want to add it only on clicked div.

<body>
  <button class="novo">Novo</button>
<div class="container">
  <div class="grupa">
    <h1>To-Do List<span id="form"><i class="fas fa-edit"></i></span></h1>
    <input type="text" placeholder="Add New Todo">
    <ul>
      <li><span><i class="fas fa-trash-alt"></i></span> Sabah</li>
    </ul>
  </div>
  <script type="text/javascript" src="Assets\JS\projekt.js">
  </script>
</body>

jS:

$("ul").on("click", "li", function(){
  $(this).toggleClass("completed");
});
$("ul").on("click", "span", function(event){
  $(this).parent().fadeOut(500, function(){
    $(this).remove();
    });
  event.stopPropagation();
});
$("input[type='text']").keypress(function(key){
  if(key.which === 13){
  var todoText = $(this).val();
  $("ul").append("<li><span><i class='fas fa-trash-alt'></i></span> " + todoText + "</li>");
  }
});
$("#form").click(function(){
    $("input[type='text']").fadeToggle(150);
});
$(".novo").on("click", function(){
  $(".container").append("<div class='grupa'><h1>To-Do List<span id='form'><i class='fas fa-edit'></i></span></h1><input type='text' placeholder='Add New Todo'><ul><li><span><i class='fas fa-trash-alt'></i></span> Sabah</li></ul></div>");
});

Thank You!!

Harun Durak
  • 25
  • 1
  • 6
  • Yes, they won't work. You attach events to the elements that are already present. try looking at `jQuery.on` for delegation of events. that'll help – Akshay Khandelwal Mar 11 '18 at 20:54

1 Answers1

2

You have to move your .on() bindings to a level higher up. That is because when you apply the .on() bindings to the <ul> element, the said element must be available in the DOM at runtime. That means that the newly added <ul>, triggered by clicking on the .novo button, will not have any JS events bounds to it.

In this case, you should move the binding to a parent element that is already present at runtime, e.g. the .container element. Refactoring your code, you can do this:

$(".container").on("click", ".grupa ul li", function(){
  $(this).toggleClass("completed");
});

$(".container").on("click", ".grupa ul span", function(event){
  $(this).parent().fadeOut(500, function(){
    $(this).remove();
    });
  event.stopPropagation();
});
Terry
  • 63,248
  • 15
  • 96
  • 118