Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

new elements don't work even with .on()

When I create new TASKs the "edit" (to save changes) and "delete" links stops working. What it wrong here?

I am using .on() but it doesn't work with new elements.

<ul id="incomplete-tasks">
 <li>
      <input type="checkbox"><label>Pay Bills</label>
      <input type="text">
      <button class="edit">Edit</button>
      <button class="delete">Delete</button>
 </li>
 </ul>
//Add new TASK
 $('#addButton').click(function(){
 $("#incomplete-tasks").append('<li><input type="checkbox"><label>' + $('#new-task').val() + '</label><input type="text"><button class="edit">Edit</button><button class="delete">Delete</button></li>')
 });

 //Show edit mode
 $("#incomplete-tasks").on("click", ".edit", function() {

 //show
 $(this).parent().toggleClass('editMode');

 //Add label value = edit field text
 var $label = $(this).children().find('label').text();
 $(this).children().find('input[type=text]').val($label);
 });

 //Save changes when "edit"is clicked again 
 $('.edit').on("click", function() {
 var value = $(this).parent().find('input[type=text]').val();
 $(this).parent().find('label').text(value);
 });

 //delete task 
 $('.delete').on("click", function() {
 $(this).parent().hide();
 });

FULL CODE -- http://codepen.io/tsalexey544/pen/LEqbpV?editors=101

1 Answer

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

So, to use the .on() method so that you can bind functions to newly created objects, you need to attach it to something further up the DOM tree than what you want to use it on. I usually just bind it to the body tag, since I know that will persist permanently on the page. Here's how you use it:

// $("  parent element or higher  ").on("  action   ","  interaction element  " function(){});
$("body").on("click", ".edit", function(){
  //Your code here...
});

Note that if you need to utilize some methods (such as preventDefault()), you will need to include a parameter for the event, in which case you would have something like this:

$("body").on("click", ".edit", function(e){
  e.preventDefault();
  //Your code here...
});

works great) thanks a lot)