-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.js
64 lines (63 loc) · 2.21 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
//variable initioalization
let inputBox=document.getElementById('input-box');
let listContainer=document.getElementById('list-container');
//a function to add tasks to the list on clicking the add button
function addTask(){
//check if the input box was empty and display an alert message to add text
if(inputBox.value===''){
alert("You must add text!");
}
//if the text is added to the input box then append the text
else{
let li=document.createElement('li');
li.innerHTML=inputBox.value;
listContainer.appendChild(li);
let span=document.createElement('span');
span.innerHTML='\u00d7';
li.appendChild(span);
saveData();
}
inputBox.value='';
}
//Adding an event listener to the Enter key of the keyboard
inputBox.addEventListener('keydown', (e) => {
if(e.key ==='Enter'){
//check if the input box was empty and display an alert message to add text
if(inputBox.value===''){
alert("You must add text!");
}
//if the text is added to the input box then append the text
else{
let li=document.createElement('li');
li.innerHTML=inputBox.value;
listContainer.appendChild(li);
let span=document.createElement('span');
span.innerHTML='\u00d7';
li.appendChild(span);
saveData();
}
inputBox.value='';
}
});
//Add event listener to the list container to either check an item or remove it from the list and save the data to the local storage
listContainer.addEventListener('click',(e) => {
//listens for a click and marks an item as checked then saves the data
if(e.target.tagName==='LI'){
e.target.classList.toggle('checked');
saveData();
}
//listens for a click, unchecks the item, and saves the data
else if(e.target.tagName==='SPAN'){
e.target.parentElement.remove();
saveData();
}
},false);
//a function to save data to a local storage
function saveData(){
localStorage.setItem('data', listContainer.innerHTML);
}
//a function to display the stored data
function showData(){
listContainer.innerHTML=localStorage.getItem('data');
}
showData();