-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
63 lines (57 loc) · 2.01 KB
/
Copy pathscript.js
File metadata and controls
63 lines (57 loc) · 2.01 KB
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
(() => {
//state variables
let toDoListArray = [];
//ui variables
const form = document.querySelector(".form");
const input = form.querySelector(".form_input");
const ul = document.querySelector(".toDoList");
//event listeners
form.addEventListener("submit", (e) => {
//prevent default behaviour - Page reload
e.preventDefault();
//give item a unique ID
let itemId = String(Date.now());
//get input value from user
let toDoItem = input.value;
//pass ID and item into functions
addItemToDOM(itemId, toDoItem);
addItemToArray(itemId, toDoItem);
//clear the input box.(this is default behaviour but we get rid of that)
input.value = "";
});
ul.addEventListener("click", (e) => {
let id = e.target.getAttribute("data-id");
if(!id) return; //thats if the user clicked in something else
//pass id through to functions
removeItemFromDOM(id);
removeItemFromArray(id);
});
//functions
function addItemToDOM(itemId, toDoItem){
//create an li
const li = document.createElement("li");
li.setAttribute("data-id", itemId);
//add toDoItem text to li
li.innerText = toDoItem;
//add li to the DOM
ul.appendChild(li);
}
function addItemToArray(itemId, toDoItem) {
//add item to array as an object with an ID so we can find and delete it later
toDoListArray.push({ itemId, toDoItem });
//print out
console.log(toDoListArray);
}
function removeItemFromDOM(id) {
//get the list item by data ID
var li= document.querySelector('[data-id="' + id + '"]');
//remove list item
ul.removeChild(li);
}
function removeItemFromArray(id) {
//create a new toDoListArray with all li's that don't match the ID
toDoListArray = toDoListArray.filter((item) => item.itemId !== id);
//printout
console.log(toDoListArray)
}
})();