바닐라JS 2주 완성반 DAY6: #3.3~3.4
2021-01-17
#3.3 Saving the User Name part Two (08:12)
html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="js-clock">
<h1>00:00</h1>
<form class="js-form form">
<input type="text" placeholder="what is your name?"/>
</form>
<h4 class="js-greetings greetings"></h4>
</div>
<script src="clock.js"></script>
<script src="greeting.js"></script>
</body>
</html>
css
.form,
.greetings{
display: none;
}
.showing{
display: block;
}
JavaScript
const form =document.querySelector(".js-form"),
input = form.querySelector("input"),
greeting= document.querySelector(".js-greetings")
const USER_LS = "currentUser",
SHOWING_CN = "showing";
function handleSubmit(event){
event.preventDefault();
const currentValue = input.value;
paintGreeting(currentValue);
saveName(currentValue);
}
function saveName(text){
localStorage.setItem(USER_LS, text);
}
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){
// he is not
askForName();
} else {
// she is
paintGreeting(currentUser);
}
}
function init() {
loadName()
}
init();
이번 강의에서는 input 태그안에 텍스트를 입력하고 enter를 누르면(submit)
브라우져 application key / value 값에 currentUser / input값 이들어가게 하게 코드를 작성했다.
일단 첫번째로 askForName이라는 메서드를 만들고
form태그에 SHOWING_CN변수의 값이 클래스명에 들어가게 설정하고
addEventListener로 "submit" 이벤트가 발생시 hadleSubmit 함수를 실행하게 코드를 작성한다.
+ 위에 써있듯 input값을 넣고 enter를 누르면 브라우져는 submit 이벤트가 발생하게 되고
미지의 곳으로 날라가고 브라우져는 새로고침을 하게되는 모습을 확인 가능한데
우리는 미지의 곳으로 날라가지 않게 저장할수 있도록 eventhandler로 handleSubmit 함수를 정의해보겠다.
handleSubmit 함수를 보면 event를 인자값으로 받아
미지의 곳으로가는걸 막아주는 preventDefault(); 함수를 쓰고
input값을 담아줄 currentValue변수 생성후
paintGreeting 함수를 사용해서 화면에 Hello currentValue 가 띄워지게 만든다
그리고 나서 localStorage에 저장하기위해 saveName함수를 만들어 currentValue를 인자값으로 받게 하고
saveName 함수에서 localStorage.setItem(USER_LS,text) 값으로 저장하게 만들어주면 된다.
#3.4 Making a To Do List part One (12:43)
html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="index.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="todo.js"></script>
<script src="clock.js"></script>
<script src="greeting.js"></script>
</body>
</html>
JavaScript
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.innerHTML="X";
const span = document.createElement("span");
span.innerText = text;
li.appendChild(span);
li.appendChild(delBtn);
toDoList.appendChild(li);
}
function handleSubmit(event){
event.preventDefault();
const currentValue = toDoInput.value;
paintToDo(currentValue);
toDoInput.value="";
}
function loadToDos(){
const toDos=localStorage.getItem(TODOS_LS)
if(toDos !== null){
}
}
function init() {
loadToDos();
toDoForm.addEventListener("submit",handleSubmit)
}
init();
이번 강의에서는 HTML 파일에 <form> 태그를 추가해서 to-do-list 목록을 받는 <input>태그를 생성하고
그아래 <ul> 태그를 생성해 <li>태그 안에 목록들이 추가되어서 list형식으로 나오게 코드를 짜보았다.
첫번째로 새로운 todo.js파일을 만들어서 그안에 작업을 했는데
첫번째로 만든 함수로는
loadToDos가 있다. 이함수는 아직 구현이 제대로 안되었다.
다음강의에서나 다룰거 같아서 여기서는 설명을 패스하겠다.
handleSubmit함수를 봐보자.
일단 이함수에서 구현한 기능들은
첫번째로 인풋값을 작성하고 엔터를 눌렀을때 submit 이벤트가 발생하고
브라우져가 초기화되는걸 방지하기 위해 event를 인자값으로 받고
preventDefault(); 함수를 사용해서 새로고침되는걸 막아준다.
그리고 이후 인풋값을 저장하는 currentValue 변수를 초기화 해주고
paintToDo(currentValue) 함수를 호출해준다. 이 함수의 정의는 handleSubmit함수 정의를 끝내고 하겠다.
그리고 인풋에 남아있는 작성된 텍스트를 없애기 위해
toDoInput.value=""; 로 공백을 주고 마무리된다.
paintToDo 함수를 봐보자.
이 함수에서는 <li>와 <button>, <span>태그들을 생성해주는 createElement 함수를 이용해서
변수 li와 delBtn,span에 각각 초기화 해준다.
초기화해주고 delBtn같은경우 X의 문자를 innerHTML로 추가해주는데
이 부분은 나중 강의에서 목록 삭제기능을 구현하기위함인거 같다.
이번 강의에서는 기능까지의 구현은 되지 않았다.
그다음으로는 span 변수에 text(currentValue) 를 저장해주고
appendChild()함수를 이용해서 각각의 생성된 태그에 추가를해주는 걸로 이 강의는 마무리된다.