Max Max - 5 months ago 8
jQuery Question

Loading HTML from localStorage breaks function of a button

I save a part of my HTML (div class="savage") in localStorage and retrieve it when the page is refreshed. The HTML in question is a text-box for input with and "add new item" button and an unordered list of items with "delete" buttons and checkboxes. After I add a few items to my list and refresh the page, the list gets loaded correctly but I can't use the add button anymore. I can click on it but nothing happens and it won't append new items to the list. If anyone can tell me what I did wrong or point me in the right direction it would be greatly appreciated.

HTML

<div class="savage">
<h1>List of exercises to do today </h1>
<h2> My workout <span id="counter"></span></h2>
<form><input type="text" id="new-text"/></form><button id="add">Add</button>
<ul id="mylist">
<li> <input type="checkbox" class="done"/>figs<button class="delete">delete</button></li>
<li><input type="checkbox" class="done"/>pine nuts<button class="delete">delete</button></li>
</ul>
</div>


And JQUERY

window.onload = function() {
if(localStorage.getItem('peterslist')) {
$('.savage').html(localStorage.getItem('peterslist'));
}
};

function updateStorage() {
var peterslist = $('.savage').html();
localStorage.setItem('peterslist', peterslist);
}


BUTTON EVENT HANDLER

$(function(){

$("#add").on('click', addListItem);
$(document).on('click', '.delete', deleteitem);
$(document).on('click', '.done', finishItem);

});

Answer

The #add is inside .savage which is changed therefore the handler linked to #add will be lost. As a result the following code

$(function(){

  $("#add").on('click', addListItem);
  $(document).on('click', '.delete', deleteitem);
  $(document).on('click', '.done', finishItem);

});

should be changed to this

$(function(){

  $(".savage").parent().on('click', "#add", addListItem);
  $(document).on('click', '.delete', deleteitem);
  $(document).on('click', '.done', finishItem);

});
Comments