본문 바로가기

코딩도 합니다/JS

[자바스크립트 js / 프로젝트7 ] 리스트 만들기 / localStorage



 

 

 

  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">
    <link rel="stylesheet" href="main.css">
    <script src="https://kit.fontawesome.com/0615dc2069.js" crossorigin="anonymous"></script>
    <title>리스트</title>
</head>
<body>
    <!-- add items -->
    <div class="addItems-container">
        <h4 class="addItems-action">알림</h4>
        <h2 class="addItems-title">리스트 추가하기</h2>
        <form action="">
            <input type="text" placeholder="내용을 입력하세요."name="" id="" class="addItems-input">
            <button type="submit" class="addItems-submit">등록</button>
        </form>
    </div>
    <!-- display items-->
    <div class="displayItems-container">
        <h4 class="displayItems-action">알림</h4>
        <h2 class="displayItems-title">등록된 내용</h2>
        <div class="grocery-list">
            <!--grocery item-->
            <!-- <div class="grocery-item">
                <h4 class="grocery-item__title">item</h4>
                <a href="#" class="grocery-item__link">
                    <i class="far fa-trash-alt"></i>
                </a> -->
            </div>
            <!-- end grocery item -->
            <button type="submit" class="displayItems-clear">전체 삭제</button>
        </div>
        
    </div>
    <script src="app.js"></script>
</body>
</html>

 

 

 

 

 

  css

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    display: grid;
    grid-template-columns: 80%;
    justify-content: center;
    margin-top: 3rem;
    background: #fff9c7;
}

.addItems-container{
    background: #ffffff;
}

.addItems-container, .displayItems-container{
    margin: 1rem 0;
    padding: 2rem;
    border-radius: 0.5rem;
    text-align: center;
    box-shadow: 0 5px 10px #272932;
}

.addItems-title, .displayItems-title{
    text-transform: capitalize;
}

.addItems-title{
    color: #555;
}

.addItems-action, .displayItems-action{
    border: 2px solid #272932;
    padding: 0.5rem 0;
    text-transform: capitalize;
    border-radius: 0.5rem;
    display: none;
}

.addItems-input{
    background: transparent;
    border: none;
    border-bottom: 1px solid #9e90a2;
    width: 100%;
    font-size: 1rem;
    padding: 0.5rem;
    color: #9e90a2;
    outline: none;
    text-transform: uppercase;
    margin-top: 20px
}

.addItems-submit,.displayItems-clear{
    display: block;
    width: 90%;
    margin: 2rem auto 0 auto;
    font-size: 1rem;
    padding: 15px 0;
    border-radius: 1rem;
    cursor: pointer;
    text-transform: capitalize;
    outline: none;
}

.addItems-submit{
    color: #555;
    background: transparent;
    border: 1px solid #555;
    transition: all 2s ease;
}

.addItems-submit:hover{
    background: #ffe869;
    color: #272932;
}

.displayItems-container{
    background: #f3f3f3;
}

.displayItems-title{
    color: #555;
    margin-bottom: 0.25rem;
}

.grocery-item{
    display:grid;
    grid-template-columns: 4fr 1fr;
    align-items: center;
    border-radius: 0.5rem;
    padding: 0.5rem;
    transition: all 1s ease-in-out;
    margin: 0.5rem 0;
}

.grocery-item:hover{
    background: #828489;
}

.grocery-item__title{
    text-align: left;
    margin-left: 0.5rem;
    font-size: 1.2rem;
    text-transform: capitalize;
    color: #272932;
}

.grocery-item__link{
    color: red;
    transition: all 2s linear;   
}

.grocery-item:hover .grocery-item__link{
    transform: scale(2);
}

.displayItems-clear{
    background: transparent;
    border: 1px solid #555;
    transition: all 2s ease;
}

.displayItems-clear{
    background: #4d7ea8;
    color:#272932;
    outline:none;
    background: transparent;
}
/*Add utility action classes */
.alert{
    color: red;
    border-color: red;
    display: block;
    margin-bottom: 0.5rem;
}

.success{
    color:rgb(32, 184, 32);
    border-color: rgb(32, 184, 32);
    display: block;
    margin-bottom: 0.5rem;
}

@media screen and (min-width: 768px){
    body{
        grid-template-columns: 50%;
    }
}

 

 

 

 

 

  js

const addItemsAction = document.querySelector('.addItems-action');
const input = document.querySelector('.addItems-input');
const submit = document.querySelector('.addItems-submit');

const list = document.querySelector('.grocery-list');
const displayItemsAction = document.querySelector('.displayItems-action');
const clear = document.querySelector('.displayItems-clear');

// event listeners 추가
//Submit listener
submit.addEventListener('click', addItem);
// local storage 체크
document.addEventListener('DOMContentLoaded', displayStorage);
// 전체 삭제
clear.addEventListener('click', removeItems);
// 하나씩 삭제
list.addEventListener('click', removeSingleItem);


// 등록
function addItem(event){
    event.preventDefault();
    let value = input.value;
    if (value === ''){
        showAction(addItemsAction, '내용을 입력해 주세요.', false);
    } else {
        showAction(addItemsAction, `'${value}'\n내용이 리스트에 등록되었습니다. `, true);
        createItem(value);
        updateStorage(value);
    }
}


// 위 '등록'함수에서 사용된다.
function showAction(element, text, value){
    if (value === true){
        element.classList.add('success');
        element.innerText = text;
        input.value = '';
        setTimeout(function(){
            element.classList.remove('success');
        }, 3000)
    } else {
        element.classList.add('alert');
        element.innerText = text;
        input.value = '';
        setTimeout(function(){
            element.classList.remove('alert');
        }, 3000)
    }
}


// 리스트 생성 
function createItem(value){
    let parent = document.createElement('div');
        parent.classList.add('grocery-item');

    // let title = document.createElement('h4');
    //     title.classList.add('grocery-item__title');

    parent.innerHTML = `<h4 class="grocery-item__title">${value}</h4>
    <a href="#" class="grocery-item__link">
        <i class="far fa-trash-alt"></i>
    </a>`

    list.appendChild(parent);
}


// 업데이트 storage
function updateStorage(value){
    let groceryList;
    
    groceryList = localStorage.getItem('groceryList') ? JSON.parse(localStorage.getItem('groceryList')) : [];

    groceryList.push(value);
    localStorage.setItem('groceryList', JSON.stringify(groceryList));
}

// local storage 내용으로 리스트 보여주기
function displayStorage(){
    let exists = localStorage.getItem('groceryList');
    
    if(exists){
        let storageItems = JSON.parse(localStorage.getItem('groceryList'));
        storageItems.forEach(function(element){
            createItem(element);
        })
    }
}


// 리스트 전체 삭제
function removeItems(){
    // local storage에서 지우기
    localStorage.removeItem('groceryList');
    let items = document.querySelectorAll('.grocery-item');
    
    if(items.length > 0){
        showAction(displayItemsAction, '전체 리스트가 삭제 되었습니다.', false);
        items.forEach(function(element){
            list.removeChild(element);
        })
    } else {
        showAction(displayItemsAction, '삭제할 리스트가 없습니다.', false);
    }
}


// 리스트 개별 삭제
function removeSingleItem(event){
    event.preventDefault();
    
    let link = event.target.parentElement;
    if(link.classList.contains('grocery-item__link')){
        let text = link.previousElementSibling.innerHTML;
        let groceryItem = event.target.parentElement.parentElement;
        // list에서 지우기

        list.removeChild(groceryItem);
        showAction(displayItemsAction,`'${text}'\n내용이 리스트에서 삭제되었습니다.`, true);

        // local storage 에서 지우기
        editStorage(text);

    }
}



function editStorage(item){
    let groceryItems = JSON.parse(localStorage.getItem('groceryList'));
    let index = groceryItems.indexOf(item);
    
    groceryItems.splice(index, 1);
    // 기존 리스트 삭제
    localStorage.removeItem('groceryList');
    // 새로운 업데이트 / 수정 목록 추가
    localStorage.setItem('groceryList', JSON.stringify(groceryItems));

}

 

 

 

 

 

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

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