What do i add to my HTML and JS file in order to save values to local storage, and read them as well as load them from local storage so that they fill into the list automatically as well as adding a clear button for clearing local storage?
let addToDoButton = document.getElementById('addToDo');
let toDoContainer = document.getElementById('toDoContainer');
let inputField = document.getElementById('inputField');
addToDoButton.addEventListener('click', function(){
var paragraph = document.createElement('p');
paragraph.classList.add('paragraph-styling');
paragraph.innerText = inputField.value;
toDoContainer.appendChild(paragraph);
inputField.value = "";
paragraph.addEventListener('click', function(){
paragraph.style.textDecoration = "line-through";
paragraph.style.color = "red";
})
paragraph.addEventListener('dblclick', function(){
toDoContainer.removeChild(paragraph);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>To Do List</title>
</head>
<body>
<label><h1>To Do List</h1></label>
<div class="container">
<input id="inputField" type="text" name="todo" id="todo">
<button id="addToDo">+</button>
<div class="to-dos" id="toDoContainer">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Try this
For some reason the snippet is not working. Kindly check out a working example here https://jsfiddle.net/rkhsxw0p/
let toDoContainer = document.getElementById('toDoContainer');
let inputField = document.getElementById('inputField');
let todos = JSON.parse(localStorage.getItem('todos') ?? '[]');
function addTodos(){
toDoContainer.innerHTML = todos.map((todo, index) => {
return `<p class="${todo.done ? 'done' : ''}" data-index="${index}">
${todo.title}
<button>x</button>
</p>`
}).join('');
}
document.getElementById('add-todo-form').addEventListener('submit', event => {
event.preventDefault();
let title = inputField.value.trim();
if( title ){
todos.push({ title: title, done: false });
inputField.value = "";
localStorage.setItem('todos', JSON.stringify(todos));
addTodos();
}
});
toDoContainer.addEventListener('click', event => {
if( event.target.tagName === 'P' ){
let index = event.target.dataset.index;
todos[index].done = !todos[index].done;
}else if( event.target.tagName === 'BUTTON' ){
let index = event.target.parentElement.dataset.index;
todos.splice(index, 1);
}
localStorage.setItem('todos', JSON.stringify(todos));
addTodos();
})
// load saved todo
addTodos();
.done {
color: red;
text-decoration: line-through;
}
<div class="container">
<form id="add-todo-form" autocomplete="off">
<input type="text" id="inputField">
<button type="submit">+</button>
</form>
<div class="to-dos" id="toDoContainer"></div>
</div>