LoginSignup
1
3

More than 3 years have passed since last update.

【あえてjavascriptのみでtodoリストを作ってみた】

Last updated at Posted at 2020-11-13

Vue.jsでtodolistを作るのはなんとなくイメージできるが、生javascriptで作るにはどうするのか気になったので作ってみることにした。

sessionにはカテゴリやタスクを追加するたびに追加するようにしたかったがそれだと、index番号が保管されず、順番がばらばらになるので毎回ページ全体ごと保存することにした。

1,まずはカテゴリを横に永遠つくれるようにする。
2,各カテゴリにタスク追加ボタン&formを設置
3,そのボタンがおされたら、formの一個うえのDOMを指定してそこにタスクを作る。
4,カテゴリの追加やタスクの追加があるたびにページ全体ごとsessionに保存
5,ページをreloadするたびsession情報を取得

1ED62026-EEED-4ED8-8032-9DABE956A9A2_4_5005_c.jpeg

session取得部分

const htmls = JSON.parse(localStorage.getItem(0));
if (htmls) {
    lists.innerHTML += htmls;
        // 配列として保存しているため「,」がそのまま表示されてしまうためここで消している。
    lists.innerHTML = lists.innerHTML.replace(/,/g, "");
}

カテゴリ追加部分

const createList = (listname) => {
    const lists = document.getElementById("lists");
    const html = `<div class="list-range">
                        <p id="keyname" class="text-center listtitle">${listname}</p>
                        <a id="delete" class="delete-list">×</a>
                        <div class="tasks"></div>
                        <p id="addCard" class="addcard">+ カードを追加</p>
                        <form id="taskForm" class="task-form" autocomplete="off" action="javascript:void(0)">
                            <input type="text" id="listname">
                            <input type="submit" value="タスクを追加">
                        </form>
                    </div>`;
    lists.innerHTML += html;
    const arrayLists = [];
    // localstarageからデータの取得&デコード
    const items = JSON.parse(localStorage.getItem(0));
    // arrayListsにitemsを配列として設置
    if(items){
        arrayLists.push(items);
    }
    arrayLists.push(html);

    deleteTaskFromLocalStorage();
    saveTaskToLocalStorage(JSON.stringify(arrayLists)); 
}

JSON.parse JSON文字列をjavascriptのオブジェクトや値にデコードする

.push() 配列の一番うしろに値を追加

JSON.stringify JavaScript のオブジェクトや値を JSON 文字列に変換

タスク追加部分

$(document).on('submit', '#taskForm', e => {
    const task = e.target.listname.value;
    e.target.style.display = "none";
    e.target.previousElementSibling.style.display = "block";
    if (task !== ""){
        e.target.previousElementSibling.previousElementSibling.innerHTML += `<p class="task">${task}</p>`;
    }

    deleteTaskFromLocalStorage();
    saveTaskToLocalStorage(JSON.stringify(lists.innerHTML)); 
});

e.target イベントを起こしたHTML
previousElementSibling 一個前のDOM要素取得

todolist全体のcode
https://github.com/KEN3pei/todolist

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3