[노마드코더] 바닐라 JS로 크롬앱 만들기 6일차(greeting, todo)
event.preventDefault
보통 이벤트는 root 에서 일어난다.
event는 일종의 거품 같은 것이다. 올라가면서 다른 모든것들이 이벤트에 반응하게 된다.
form을 제출하는 이벤트가 발생하면 이벤트는 document까지 계속 위로 올라간다.
그 document는 프로그램 되어진대로 다른 곳으로 가고, 페이지는 새로고침 된다.
event.preventDefault()는 이런 이벤트의 디폴트 동작을 막는 방법이다.
이경우 엔터를 눌러 submit을 해도 다른곳으로 가지 않는다.
local stroage 는 URLs를 기초로 동작한다.
때문에 한 웹사이트가 다른 웹사이트의 local storage에 접근하지 못한다.
document.createElement()
무언가를 생성하기를 원할때 사용한다.
지정한 tagName의 HTML요소를 만들어 반환한다.
Node.appendChlild()
한노드를 그의 부모 element 안에 넣는다.
부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙인다.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Something</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="js-clock">
<h1>00:00</h1>
</div>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
<form class="js-toDoForm">
<input type="text=" placeholder="Write a to do" />
</form>
<ul class="js-toDoList"></ul>
<script src="clock.js"></script>
<script src="greeting.js"></script>
<script src="todo.js"></script>
</body>
</html>
greeting.js
const form=document.querySelector(".js-form"),
input=form.querySelector("input"),
greeting=document.querySelector(".js-greetings");
const USER_LS="currentUser",
SHOWING_CN="showing";
function saveName(text){ //로컬 스토리지에 이름을 저장
localStorage.setItem(USER_LS, text);
}
function handleSubmit(event){
event.preventDefault(); //제출되는 동작을 막는다.
const currentValue = input.value; //input 이름 값
paintGreetings(currentValue);
saveName(currentValue);
}
function askForName(){
form.classList.add(SHOWING_CN);
form.addEventListener("submit",handleSubmit);
}
function paintGreeting(text){
form.classList.remove(SHOWING_CN); //텍스트를 색칠하려면, 폼을 숨겨야 함
greeting.classList.add(SHOWING_CN);
greeting.innerText = `Hello ${text}`;
}
function loadName(){
const currentUser=localStorage.getItem(USER_LS);
if(currentUser===null){ //현재유저가 없으면 이름을 물어보는 폼을 보여줌
askForName();
}else{ //현재 유저가 있으면 로컬스토리지에서 가져온 이름을 paint
paintGreeting(currentUser);
}
}
function init(){
loadName();
}
init();
현재 유저 이름이 없으면 이름을 물어보는 폼을 가져오는 askForName()함수를 실행한다.
등록을 할경우 handleSubmit함수가 실행돼 이때 input 값을 가져와 paintGreeting 함수에 그 값을 전달해 실행한다.
이름을 등록하는 폼을 숨기고, Hello {이름} 텍스트가 보여진다.
todo.js
const toDoForm = document.querySelector(".js-toDoForm"),
toDoInput = toDoForm.querySelector("input"),
toDoList = document.querySelector(".js-toDoList");
const TODOS_LS = 'toDos';
function paintToDo(text){
const li = document.createElement("li");
const delBtn = document.createElement("button");
delBtn.innerText = "❌";
const span = document.createElement("span");
span.innerText = text;
li.appendChild(delBtn);
li.appendChild(span);
toDoList.appendChild(li);
}
function handleSubmit(event){
event.preventDefault();
const currentValue=toDoInput.value;
paintToDo(currentValue);
toDoInput.value=""; //submit했을때 안을 다시 비워줌
}
function loadToDos(){
const toDos=localStorage.getItem(TODOS_LS);
if(toDos !== null){
}
}
function init(){
loadToDos();
toDoForm.addEventListener("submit", handleSubmit);
}
init();
todo.js도 greeting.js와 비슷하지만 다른 점이라면 항상 폼을 보여주기 때문에 showing 클래스를 사용하지 않는다는 점이다.
paintToDo() 함수 부분에서는
li, delete 버튼 span을 생성한 후 li안에 버튼과 span을 append하고 마지막으로 li를 ul에 append한다.
이때 버튼의 이모지는 텍스트 취급!
js 안에서 요소들을 추가하고 제거하고, 정보를 로컬 스토리지에 저장하고 이런것들이 재미지다~