본문 바로가기
JS

[JS] To do list 제작

by 사과넹 2020. 11. 12.
반응형

바닐라 자바스크립트를 이용해 혼자 to do list를 만들어보았다.

 

localStorage를 활용해 F5시에도 list가 날아가지 않도록 짜는데 저장하는건 쉽지만 f5후 다시 거기서 가져오는 것까지 생각하니 여간 힘든 일이 아니었다...

 

어찌어찌 구글링하며 만들긴했는데 내가 짠 코드의 한계는 아직 수정하지 못했다...

 

localStorage에 다른 정보가 있으면 제대로 작동하지 않는다는 점...

니콜라스쌤 강의에서는 JSON 메서드를 사용해서 거기에 걸리지않는 것같던데, 그걸 사용하지 않아서인지,

접근 방법이 좋지 못해서인지 여튼 아무리 생각해도 돌파구가 생각나지 않아 이대로 포스팅... 아쉽다... 


html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="clock_box">
        <h1>00:00:00</h1>
    </div>
    <form action="" class="todo_form">
        <input type="text" placeholder="무엇을 해야하나요?" />
        <button type="submit">추가</button>
    </form>
    <ul>
    </ul>

<script src="clock.js"></script>
<script type="text/javascript" src="hi_there.js"></script>
<script src="todolist.js"></script>
</body>
</html>

 

css

body{
    background-color: #35adb1;
  }
  
  h1{
    color:#e9c731;
    font-size: 8em;
    text-align: center;
  }
  
  .hidden{
    display :none;
  }

  .fa-times{
    color: red;
    font-size: 1.1em;
  

 

JS

const todo_form = document.querySelector('.todo_form');
const todo_input = todo_form.querySelector('input');
const create_btn = todo_form.querySelector('button');
const list_parent = document.querySelector('ul');

const local_key = [];
const local_value = [];

load_list();
continue_list();

function append_list(){ // input에 text입력시 ul의 자식으로 li 생성되며 textnode 추가됨
    const list_content = todo_input.value; 
    const list_child = document.createElement('li');
    list_parent.appendChild(list_child);
    list_child.innerText = list_content;
    list_child.setAttribute('id','list'+local_value.length);
    
    append_delete(list_child);
    save_list(list_content); // 배열과 localStorage에 저장 함수 실행
}

function append_delete(parent_element){
    const delete_btn = document.createElement('button');
    delete_btn.classList.add('fas','fa-times');
    parent_element.appendChild(delete_btn);

    delete_btn.onclick = function(){
        const btn_parent = delete_btn.parentElement;
        for(var i=0;i<localStorage.length;i++){
            if(btn_parent.id === localStorage.key(i)){ 
                const a = localStorage.getItem(localStorage.key(i));
                const b = local_value.indexOf(a);

                local_value.splice(b,1);
                local_key.splice(0,1);
                localStorage.removeItem(localStorage.key(i));
            }
        }
        btn_parent.remove(); 
    }
}


function save_list(text){
    // li에 입력한 값을 local_value 배열에 넣고, 동시에 local_key에 'list' 단어를 배열에 추가
    local_value.push(text);
    local_key.push('list');

    // 배열에 추가된 값을 localStorage에 key / value 한 쌍으로 저장시킴
    localStorage.setItem('list'+localStorage.length,local_value[localStorage.length]);
    
}

function load_list(){ // F5시 바로 실행
    // localStorage에 list0 key가 존재하면 (추가된 리스트가 있는지 없는지 확인)
    // localStorage에 있는 값들을 ul의 자식 li에 textnode로 추가함
    const saved_list = localStorage.getItem('list0');
    if(saved_list !== null){
        for(var i=localStorage.length-1; i>=0; i--){
            const load_value = localStorage.getItem(localStorage.key(i));
            const list_child = document.createElement('li');
            list_parent.appendChild(list_child);
            list_child.innerText = load_value;
            list_child.setAttribute('id','list'+i);

            append_delete(list_child);
        }
    }
}

function continue_list(){ // F5시 바로 실행
    // localStorage 저장 값을 리스트에 채워넣음
    for(var i=0;i<list_parent.childElementCount;i++){
        local_key.push('list');
        local_value.push(list_parent.children[i].innerText);
    }
}

function create_list(event){
    event.preventDefault(); // submit시 input 값이 날아가지 않게 이벤트 막음
    if(!todo_input.value){
        alert('내용을 입력해주세요.');
    }else{
        append_list(); // li 추가 함수
    }
    todo_input.value = ''; // submit 후 input clear
}

function init(){
    todo_form.addEventListener('submit',create_list);
}

init();

 

 

728x90
반응형

'JS' 카테고리의 다른 글

Vanilla JS로 SPA router 기능 만들기  (0) 2024.04.14
[JS] 로그인/회원가입 페이지 만들기  (0) 2020.12.30
[JS] var, let, const 차이점  (0) 2020.10.27
[JS] 새로운 객체 만들기 (new)  (0) 2020.10.22
[JS] localStorage 이용하기  (0) 2020.10.22