今回はJavaScriptの練習も込めてTODOlistを作りました。
まずは、コードを紹介します。↓
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">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</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" placeholder="TODOを入力" class="form-control">
</form>
<ul class="list-group text-secondary" id="ul"></ul>
</div>
<script src="index.js"></script>
</body>
</html>
javascriptのコード
const formget = document.getElementById("form");
const inputget = document.getElementById("input");
const ulget = document.getElementById("ul");
const todos = JSON.parse(localStorage.getItem("todos"));
if(todos){
todos.forEach(todo => {
add(todo);
});
}
formget.addEventListener("submit",function(event){
event.preventDefault();
add();
});
function add(todo){
let todoText = input.value;
if(todo){
todoText=todo.text;
}
if(todoText){
const li = document.createElement("li");
li.innerText = todoText;
li.classList.add("list-group-item");
if(todo && todo.completed){
li.classList.add("text-decoration-line-through");
}
li.addEventListener("contextmenu",function(event){
event.preventDefault();
li.remove();
saveDate();
});
li.addEventListener("click",function(){
li.classList.toggle("text-decoration-line-through");
saveDate();
});
ulget.appendChild(li);
input.value = "";
saveDate();
}
}
function saveDate(){
const lists = document.querySelectorAll("li");
let todos = [];
lists.forEach(list => {
let todo = {
text: list.innerText,
completed: list.classList.contains
("text-decoration-line-through")
};
todos.push(todo);
});
localStorage.setItem("todos",JSON.stringify(todos));
}
使い方
#つかってみてね!
読んでくれてありがとう。
クリスマスまで残り23日!!