본문 바로가기

코딩도 합니다/JS

[자바스크립트 js / 프로젝트 7] to do list 만들기



안녕하세요.

디자인도 하고, 개발도 하는 '디발자 뚝딱'입니다.

 

이번 포스팅에서는

자바스크립트로 to do list 만드는 방법에 대해 공유할게요!

 

 

 

 

 

  html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <!-- bootstrap css -->
 <link rel="stylesheet" href="css/bootstrap.min.css">
 <!-- main css -->
 <link rel="stylesheet" href="css/main.css">
 <!-- google fonts -->
 <link href="https://fonts.googleapis.com/css?family=Courgette" rel="stylesheet">

 <!-- font awesome -->
 <link rel="stylesheet" href="css/all.css">
 <title>Grocery Item</title>
 <style>
 </style>
</head>

<body>
 <div class="container">
  <div class="row">
   <div class="col mx-auto col-md-8 mt-3 text-center">
    <div class="alert text-capitalize feedback">
     write value for item
    </div>
    <!-- form -->
    <form id="itemForm" class="my-3">
     <h3 class="text-capitalize mb-4">to do list</h3>
     <div class="input-group">
      <input type="text" class="form-control text-capitalize" id="itemInput" placeholder="name...">
      <div class="input-group-append">
       <button class="btn btn-green text-capitalize" type="submit">add item</button>
      </div>
     </div>
    </form>
    <div class="item-container">
     <!-- end of form  -->
     <div class="item-list my-5">
      <!-- single item -->
      <!-- <div class="item my-3">
      <h5 class="item-name text-capitalize">laundry</h5>
      <div class="item-icons">
       <a href="#" class="complete-item mx-2 item-icon"><i class="far fa-check-circle"></i></a>
       <a href="#" class="edit-item mx-2 item-icon"><i class="far fa-edit"></i></a>
       <a href="#" class="delete-item item-icon"><i class="far fa-times-circle"></i></a>
      </div>
     </div> -->
      <!-- end of single item -->
     </div>
     <button type="button" class="btn btn-green my-3 text-capitalize" id="clear-list">clear items</button>
    </div>
   </div>
  </div>
 </div>




 <!-- jquery -->
 <script src="js/jquery-3.3.1.min.js"></script>
 <!-- bootstrap js -->
 <script src="js/bootstrap.bundle.min.js"></script>
 <!-- script js -->
 <script src="js/app.js"></script>
</body>

</html>

 

 

 

 

 

  js

const form = document.querySelector('#itemForm');
const itemInput = document.querySelector('#itemInput');
const itemList = document.querySelector('.item-list');
const feedback = document.querySelector('.feedback');
const clearButton = document.querySelector('#clear-list');

let todoItems = [];


// 아이콘 기능들
const handleItem = function(itemName){

    const items = itemList.querySelectorAll('.item');
 
    items.forEach(function(item){
        
        if(item.querySelector('.item-name').textContent === itemName){
            // 완료 시
            item.querySelector('.complete-item').addEventListener('click', function(){
                item.querySelector('.item-name').classList.toggle('completed');
                this.classList.toggle('visibility');
            });
            // 수정 : 현재 코드에서는 삭제와 기능 같음
            item.querySelector('.edit-item').addEventListener('click', function(){
                itemInput.value = itemName;
                itemList.removeChild(item);

                todoItems = todoItems.filter(function(item){
                    return item !== itemName;
                });
            });
            // 삭제
            item.querySelector('.delete-item').addEventListener('click', function(){
                debugger;
                itemList.removeChild(item);

                todoItems = todoItems.filter(function(item){
                    return item !== itemName;
                });

                showFeedback('item delete', 'success');
            })
        }
    })
}


// 리스트 삭제
const removeItem = function(item){
    console.log(item);
    const removeIndex = (todoItems.indexOf(item));
    console.log(removeIndex);
    todoItems.splice(removeIndex, 1);
}


// 리스트 생성 및 아이콘 추가
const getList = function(todoItems){
    itemList.innerHTML = '';

        todoItems.forEach(function(item){
            itemList.insertAdjacentHTML('beforeend', `<div class="item my-3"><h5 class="item-name text-capitalize">${item}</h5><div class="item-icons"><a href="#" class="complete-item mx-2 item-icon"><i class="far fa-check-circle"></i></a><a href="#" class="edit-item mx-2 item-icon"><i class="far fa-edit"></i></a><a href="#" class="delete-item item-icon"><i class="far fa-times-circle"></i></a></div></div>` );

            handleItem(item);
        });
}



// JSON데이터를 string으로 변환
const getLocalStorage = function(){

    const todoStorage = localStorage.getItem('todoItems');
    if (todoStorage === 'undefined' || todoStorage === null){
        todoItems = [];
    } else {
        todoItems = JSON.parse(todoStorage);
        getList(todoItems);
    }
}


// JSON으로 데이터를 변환
const setLocalStorage = function(todoItems){
    localStorage.setItem('todoItems', JSON.stringify(todoItems));
}


// 페이지에서 로컬 스토리지 가져오기
getLocalStorage();


// 로컬 스토리지를 포함해 리스트 추가
form.addEventListener('submit', function(e){ 
    e.preventDefault();
    const itemName = itemInput.value;
    
    if (itemName.length === 0){
        feedback.innerHTML = 'Please Enter Valid Value';
        feedback.classList.add('showItem', 'alert-danger');
        setTimeout(
            function(){
                feedback.classList.remove('showItem');
                }, 3000);
    } else {
        todoItems.push(itemName);
        setLocalStorage(todoItems);
        getList(todoItems);
        // 아이콘에 이벤트 넣기
        // handleItem(itemName);
    }
    
    itemInput.value = '';

    });

// 리스트 모든 항목 삭제
clearButton.addEventListener('click', function(){
    todoItems = [];
    localStorage.clear();
    getList(todoItems);
})

해당 키워드를 검색해서 공부하기!

localStorage

setLocalStorage

splice()

indexOf()

insertAdjacentHTML()

JSON.parse()

JSON.stringify()

clear()

 

 

 

 

  css

:root {
  --mainWhite: #f5f5f5;
  --mainGreen: #80cfa9;
  --mainBlack: #333333;
  --mainRed: #d62828;
  --mainBlue: #11b5e4;
}
body {
  background: var(--mainWhite);
  color: #333333;
}
.btn-green {
  border-color: var(--mainGreen);
  background: transparent;
  color: var(--mainGreen);
}
.btn-green:hover {
  background: var(--mainGreen);
  color: var(--mainBlack);
}
.form-control {
  border-color: var(--mainGreen) !important;
}

.feedback {
  display: none;
}
.item {
  display: flex;
  justify-content: space-between;
}
.item-icon {
  font-size: 1.2rem;
  cursor: pointer;
}
.complete-item {
  color: var(--mainGreen);
}
.complete-item:hover {
  color: var(--mainGreen);
}
.edit-item {
  color: var(--mainBlue);
}
.edit-item:hover {
  color: var(--mainBlue);
}
.delete-item {
  color: var(--mainRed);
}
.delete-item:hover {
  color: var(--mainRed);
}
.completed {
  text-decoration: line-through;
  opacity: 0.5;
}
.visibility {
  opacity: 0.5;
}
.showItem {
  display: block;
}

 

 

 

 

 

위 코드는 아래 링크에 있는 자바스크립트 프로젝트를 활용 및 참고하여 작업하였습니다.

https://jsbeginners.com/javascript-projects-for-beginners/#below-list

 

100+ JavaScript Projects for Beginners! [ Solutions Provided! ]

Looking for JavaScript projects to get more JavaScript practice? Here's a list of over 100 javascript projects for beginners!

jsbeginners.com

 

728x90