-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
61 lines (55 loc) · 1.8 KB
/
script.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
// IIFE
(() => {
// state variables
let toDoListArray = [];
// variables
const form = document.querySelector('.form');
const input = document.querySelector('.form_input');
const ul = document.querySelector('.toDoList');
// event listeners
form.addEventListener('submit', (e) => {
// prevent default behavior - Page reload
e.preventDefault();
// give item a unique ID
let itemId = String(Date.now());
// get/assign input value
let toDoItem = input.value;
// pass ID and item into functions
addItemToDOM(itemId, toDoItem);
addItemToArray(itemId, toDoItem);
// clear the input box. (this is default behavior but we got rid of that)
input.value = '';
});
ul.addEventListener('click', (e) => {
let id = e.target.getAttribute('data-id');
if (!id) return; // user clicked in something else
// pass id through to functions
removeItemFromDOM(id);
removeItemFromArray(id);
});
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 });
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);
console.log(toDoListArray);
}
})();