index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <title>Document</title> </head> <body class="bg-light"> <div class="container w-75"> <h1 class="text-center text-info my-4">TODO</h1> <form id="form" class="mb-4"> <input type="text" id="input" class="form-control" placeholder="TODOを入力" autocomplete="off"> </form> <ul id="ul"></ul> </div> <script src="index.js"></script> </body> </html>
index.js
const form = document.getElementById("form"); const input = document.getElementById("input"); const ul = document.getElementById("ul"); const todos = JSON.parse(localStorage.getItem("todos")); if (todos) { todos.forEach(todo => { add(todo); }) } form.addEventListener("submit", function (event) { event.preventDefault(); add(); }) function add(todo) { let todoText = input.value; if(todo) { todoText = todo; } if (todoText) { const li = document.createElement("li"); li.innerText = todoText; li.classList.add("list-group-item"); li.addEventListener("contextmenu", function (event) { event.preventDefault(); li.remove(); saveData(); }); li.addEventListener("click", function () { li.classList.toggle ("text-decoration-line-through"); }) ul.appendChild(li); input.value = ""; saveData(); } } function saveData() { const lists = document.querySelectorAll("li"); let todos = []; lists.forEach(list => { todos.push(list.innerText); }); localStorage.setItem("todos", JSON.stringify(todos)); }