Skip to content

Instantly share code, notes, and snippets.

@LucienLee
Last active August 29, 2015 14:08
Show Gist options
  • Save LucienLee/058964d07f081080dc33 to your computer and use it in GitHub Desktop.
Save LucienLee/058964d07f081080dc33 to your computer and use it in GitHub Desktop.
list example
var $list = $('ul');
// make an <li> element
var makeItem = function(text){
var $li = $('<li><input type="text"><span></span></li>');
if(text){
$li.find('input').val(text);
$li.find('span').text(text);
}
return $li;
};
// save all li span
var saveItems = function(){
var data = [];
$list.find('li').each(function(){
data.push($(this).text());
});
//save to localstorage
localStorage.list = JSON.stringify(data)
};
// sortable list
// save item after sort
// initialize dialog
// $('#remove-all-dialog').dialog({
// autoOpen: false,
// resizable: false,
// modal: true,
// buttons: {
// "Yes": function(){
// //list empty
// },
// "Cancel": function(){
// }
// }
// });
// load from localStorage
if(localStorage.list){
$.each(JSON.parse(localStorage.list), function(){
makeItem(this).appendTo($list);
});
}
// event handlers
$('.add-item').click(function(){
//add editing class and prepend. then focus it.
var item = makeItem().addClass("is-editing").prependTo($list);
item.find('input').focus();
});
$list.on('keypress', 'input', function(e){
var $li;
if(e.which === 13){
$li = $(this).parents('li');
$li.find('span').text($li.find('input').val());
$li.removeClass('is-editing');
// save into localStorage
saveItems();
}
});
//dialog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment