-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
69 lines (56 loc) · 1.91 KB
/
main.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
65
66
67
68
69
document.addEventListener+++++'DOMContentLoaded', function() {
loadTasks();
});
function addTask() {
var taskInput = document.getElementById('single-task');
var taskName = taskInput.value;
if (taskName.trim() === '') {
alert("Please enter a task.");
return;
}
var newElement = createTaskElement(taskName);
document.querySelector('.listofelements').appendChild(newElement);
saveTasksToLocalStorage();
taskInput.value = '';
}
function createTaskElement(taskName) {
var newElement = document.createElement('div');
newElement.className = 'elements';
var mainContent = document.createElement('div');
mainContent.className = 'maincontent';
var taskTitle = document.createElement('h1');
taskTitle.textContent = taskName;
var deleteButton = document.createElement('button');
deleteButton.className = 'deletebutton';
deleteButton.innerHTML = '×';
deleteButton.addEventListener('click', function() {
newElement.remove();
saveTasksToLocalStorage();
});
mainContent.appendChild(taskTitle);
mainContent.appendChild(deleteButton);
newElement.appendChild(mainContent);
return newElement;
}
function saveTasksToLocalStorage() {
var tasks = document.querySelectorAll('.elements');
var tasksArray = [];
tasks.forEach(function(task) {
tasksArray.push(task.querySelector('h1').textContent);
});
localStorage.setItem('tasks', JSON.stringify(tasksArray));
}
function loadTasks() {
var tasks = localStorage.getItem('tasks');
if (tasks) {
tasks = JSON.parse(tasks);
tasks.forEach(function(task) {
var newElement = createTaskElement(task);
document.querySelector('.listofelements').appendChild(newElement);
});
}
}
document.getElementById('task-area').addEventListener('submit', function(event) {
event.preventDefault();
addTask();
});