toDoList 만들기

» JavaScript

To Do List

웬만하면 코드 주석에 설명적어놨음

HTML CODE

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="reset.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Do+Hyeon&family=Raleway:wght@500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    <link rel="stylesheet" href="scss/mobile.scss">
    <title>To Do List</title>
</head>
<body>
    <div id="sub--body">
        <header>
            <h1>To Do List</h1>
        </header>
        <nav>
            <form class="toDoForm" action="submit">
                <input type="text">
                <button>
                    <i class="fas fa-check"></i>
                </button>
            </form>
        </nav>
        <main>
            <ul class="toDoList"></ul>
        </main>
    </div>

    <script src="app.js"></script>
</body>
</html>

JS CODE

const form = document.querySelector('.toDoForm'),
    input = form.querySelector('input');
const list = document.querySelector('.toDoList')

const TODOS_LS = 'toDos';

let toDos = []; // 나중에 toDoObj라는 객체를 넣어줄 빈 Array 생성

function deleteToDo(event) {
    const btn = event.target; // 클릭된 button의 event를 btn 상수로 할당
    const li = btn.parentNode; // btn의 부모 태그를 li란 상수로 할당
    list.removeChild(li); // 해당 태그 삭제
    const cleanToDos = toDos.filter(function(toDo) {
        // filter함수는 array의 모든 요소들에 함수를 실행한 뒤, 값이 true인 것만 가져와서 새로운 Array로 반환
        return toDo.id !== parseInt(li.id);
        // parseInt는 정수로 반환해주는 함수인데 정수로 바뀐 li.id는 toDo.id 와 같지 않다라고 반환
        // 결국엔 반환되는 것이 없게 만들어서 선택된 li안에 내용까지 지우는 것
    });
    toDos = cleanToDos; // toDos의 해당 li는 없어지게 됨
    saveToDos(); // localStorage에 해당 내용 업데이트
}

function saveToDos() { // localstorage에 투두리스트를 저장하는 함수
    localStorage.setItem(TODOS_LS, JSON.stringify(toDos));
    // JSON.stringify 함수를 사용해서 자바스크립트 object를 string으로 바꿔줌
}

function writeToDo(text) { // input 값을 text란 파라미터로 받음
    const li = document.createElement('li'); // ul밑으로 list를 만들어줄 li 태그 생성
    const delBtn = document.createElement('button'); // li를 지우기 위한 button 태그 생성
    const span = document.createElement('span'); // text 값을 보여줄 span 태그 생성
    const newId = toDos.length + 1; // toDos는 Array임, Array의 length에 +1씩해서 id값을 주기 위해 만든 상수
    delBtn.innerText = 'x'; // 아이콘으로 바꿀수도 있음
    delBtn.addEventListener('click', deleteToDo); // delBtn이 클릭되면 이벤트 전달
    span.innerText = text; // text 값을 span 태그안에 넣어줌
    li.appendChild(delBtn); // li 태그의 자식 태그로 버튼을 삽입
    li.appendChild(span); // li 태그의 자식 태그로 span 태그를 삽입
    li.id = newId; // li태그의 id 속성을 object의 id와 같게 함
    list.appendChild(li); // 위에서 설정한 li 태그들을 최종적으로 list에 삽입
    const toDoObj = { // Array에 집어넣기위해 객체로 묶어줌
        text: text,
        id : newId
    };
    toDos.push(toDoObj); // toDos라는 Array 안에 toDoObj 객체를 넣음
    saveToDos(); // localStorage로 저장하기 위해 값을 보냄
}

function catchValue(event) { // event 파라미터로 값을 받아줌
    event.preventDefault(); // 이벤트가 발생해도 새로고침 되지않게 해줌
    const toDoValue = input.value; // input안의 값을 상수에 담아줌
    writeToDo(toDoValue); // input 값을 writeToDo 함수의 파라미터로 전달
    input.value = ''; // input 값을 다시 빈칸으로 만듬
}

function init() {
    form.addEventListener('submit', catchValue); // form 안에 값을 받아서 catchValue함수로 넘겨줌
}

init(); // 이거 없으면 init 실행이 안되니깐 실행시켜주려고 적음