var input = document.getElementById('todo-input'); var todoList = document.getElementById("todo-list"); var todos = []; if(typeof(Storage) !== "undefined"){ var localTodos = localStorage.getItem("todos"); if(localTodos == null){ //first run... } else { console.log("Existing todos found."); todos = JSON.parse(localTodos); console.log(todos); todos.forEach(element => { console.log(element); addTodo(element.text, element.complete); }); } } else { addTodo("There is no web storage support for this session", false); } window.onbeforeunload = function(){ localStorage.clear(); localStorage.setItem("todos", JSON.stringify(todos)); } input.onkeyup = (e) => { if(e.keyCode == 13){ addTodo(); input.value = ""; } } function addTodo(text, completed){ var todoText = input.value; if(text){ todoText = text; } else { //new element todos.push({ "text": todoText, "complete": completed } ); } if(todoText == ""){ return; } var newTodo = document.createElement("li"); var newTodoDiv = document.createElement("div"); var newTodoCheck = document.createElement("input"); newTodoCheck.type = 'checkbox'; newTodoCheck.onchange = (e) => { var index = Array.from(todoList.children).indexOf(e.target.parentNode.parentNode); console.log(index); todos[index].complete = e.target.checked; e.target.parentNode.parentNode.classList.toggle("complete"); } var newTodoContent = document.createElement("p"); newTodoContent.innerHTML = todoText; if(completed){ newTodoCheck.checked = true; newTodoContent.classList.add("complete"); } var newTodoRemoveButton = document.createElement("button"); newTodoRemoveButton.innerHTML = "×" newTodoRemoveButton.onclick = removeTodo; newTodoDiv.classList.add("todo-item"); newTodoDiv.appendChild(newTodoCheck); newTodoDiv.appendChild(newTodoContent); newTodoDiv.appendChild(newTodoRemoveButton); newTodo.appendChild(newTodoDiv); if(completed){ newTodo.classList.toggle("complete") } todoList.appendChild(newTodo); } function removeTodo(e){ var index = Array.from(todoList.children).indexOf(e.target.parentNode.parentNode); console.log(index); todos.splice(index,1); e.target.parentNode.parentNode.remove(); } function resetLocalStorage(){ todos = []; localStorage.clear(); location.reload(); }