-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToDo.js
64 lines (61 loc) · 2.39 KB
/
ToDo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// This function gets the task from input:
function get_todos() {
// This creates an array of tasks that are inputed:
var todos = new Array();
// This pulls the task that was saved in the web browser's memory:
var todos_str = localStorage.getItem("todo");
/* If input !== null, then "JSON.parse()" will communicate with the web browser to make the task a JS object: */
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
/* This function adds the inputed task to the "get_todos()" array: */
function add() {
// This takes the inputed task & creates a variable of it: */
var task = document.getElementById("task").value;
var todos = get_todos();
// This adds a new task to the array's end:
todos.push(task);
// This converts the task input to a JSON string:
localStorage.setItem("todo", JSON.stringify(todos));
document.getElementById("task").value = "";
show();
return false;
}
// This function keeps the tasks permanetly displayed on the screen:
function show() {
// This sets the task that was retrieved as a variable:
var todos = get_todos();
// This sets up each task as an unordered list:
var html = "<ui>";
// This displays a task to the list in the order that it was inputed:
for (var i = 0; i < todos.length; i++) {
/* This also displays the task as a list, and creates the button with the "x": */
html += `<li> ${todos[i]}. <button class="remove" id=${[i]}>x</button></li>`;
}
html += "</ui>";
// This displays the task as a list:
document.getElementById("todos").innerHTML = html;
/* THis tells the browser how to display the todo array after an item has been removed: */
var buttons = document.getElementsByClassName("remove");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", remove);
}
}
// This displays the inputed task when the "Add Item" button is clicked:
document.getElementById("add").addEventListener("click", add);
// This will keep the inputs displayed permanently on the screen:
show();
/* ==============================================
Step 421 ToDo Assignment
============================================ */
function remove() {
var id = this.getAttribute("id");
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem("todo", JSON.stringify(todos));
/* This looks in the show() how to display a removed item on the screen: */
show();
return false;
}