바닐라 JS로 크롬 앱 만들기 (#4 Login)
Input Values
input.html
app.js
// const loginForm = document.getElementById("login-form");
// const logininput = loginForm.querySelector("input");
// const loginutton = loginForm.querySelector("button");
const logininput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");
function onLoginBtnClick(){
console.log(logininput.value)
}
loginButton.addEventListener("click", onLoginBtnClick);
.value 을 하면 input에 입력한 값을 읽어 올 수 있다.
Form Submission
form : 사용자가 입력한 정보를 서버에 전송할 떄 사용하는 것
const logininput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");
function onLoginBtnClick(){
const username = logininput.value;
if (username === '') {
alert('Please write your Name');
} else if (username.length > 15) {
// 15글자를 초과하면 경고창
alert('name is too longer!');
} else {
alert('hello ' + username);
}
}
loginButton.addEventListener("click", onLoginBtnClick);
✔ input 의 유효성 검사를 작동시키기 위해서는 input 이 form 안에 있어야 한다.
✔ html의 도움을 활용하려면, form안에 위치시켜야 한다.
✔ input 안에 있는 button 을 누르거나 type 이 submit인 input 을 클릭하면 내가 작성한 form이 submit된다.
Events
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>MOMENTUM App</title>
</head>
<body>
<form id="login-form">
<input type="text" placeholder="what is your name?"/>
<button>Lon In</button>
</form>
<script src="app.js"></script>
</body>
</html>
app.js
const loginForm = document.getElementById("login-form");
const logininput = document.querySelector("#login-form input");
function onLoginSubmit(){
const username = logininput.value;
console.log(username)
}
// 지정한 event가 발생하면, 브라우저가 function을 실행시켜 준다.
loginForm.addEventListener("submit",onLoginSubmit);
submit : 브라우저가 새로고침된다. form submit 의 기본 동작이다.
브라우저는 form에서 엔터를 치거나 submit 타입의 input 혹은 버튼을 클릭할 때,
웹 페이지를 재실행 하도록 되어있어 있다.
addEventListener()에서 function을 받을 때 '()'을 추가하지않고, function의 이름만 적어준다.
'()' 를 추가하는 건 function을 '즉시' 실행한다는 뜻이다.
✔ submit 컨트롤하기
브라우저의 기본 동작이 발생되지 않도록 막기 → preventDefault
const loginForm = document.getElementById("login-form");
const logininput = document.querySelector("#login-form input");
function onLoginSubmit(event){
event.preventDefault();
console.log(logininput.value);
}
loginForm.addEventListener("submit",onLoginSubmit);
→ 버튼을 클릭해도 새로고침이 되지 않는다.
Getting Username
- 이름을 입력 받았을 때 form 을 없애고 싶다면.
classname 으로 hidden 를 추가해서 css에서 display none 처리
style.css
.hidden {
display: none;
}
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>MOMENTUM App</title>
</head>
<body>
<form id="login-form">
<input type="text" placeholder="what is your name?"/>
<button>Lon In</button>
</form>
<h1 id="greeting" class="hidden"></h1>
<script src="app.js"></script>
</body>
</html>
app.js
const loginForm = document.getElementById("login-form");
const logininput = document.querySelector("#login-form input");
const greeting = document.querySelector("#greeting");
const HIDDEN_CLASSNAME = "hidden";
function onLoginSubmit(event){
event.preventDefault();
const username = logininput.value;
loginForm.classList.add(HIDDEN_CLASSNAME);
console.log(username); // form 은 hidden 되고 input 값은 console 에 출력
greeting.innerText = `Hello ${username}`;
greeting.classList.remove(HIDDEN_CLASSNAME);
}
loginForm.addEventListener("submit",onLoginSubmit);
Saving Username
local Storage
브라우저에 값을 저장할 수 있게 해준다.
localstorage.setItem : local storage에 정보를 저장
localstorage.getItem : local storage에 저장한 값 불러오기
localstorage.removeItem : 저장된 값 지우기
localStorage.setItem("USERNAME_KEY", username);
localstorage 에 저장된 내용 확인 가능
Loading Username
✅ 새로고침 할 때 localstorage에 값이 있으면 이름을 보여주고 아니면 name을 입력받는 창이 나오도록
localstorage에 key가 username 으로 저장된 value를 가져온다.
값이 없으면 login-form에 classname을 hidden을 지우고, 값이 있으면 함수 paintGreetings 실행
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>MOMENTUM App</title>
</head>
<body>
<form id="login-form" class="hidden">
<input type="text" placeholder="what is your name?"/>
<button>Lon In</button>
</form>
<h1 id="greeting" class="hidden"></h1>
<script src="app.js"></script>
</body>
</html>
app.js
const loginForm = document.getElementById("login-form");
const logininput = document.querySelector("#login-form input");
const greeting = document.querySelector("#greeting");
const HIDDEN_CLASSNAME = "hidden";
const USERNAME_KEY = "username";
function onLoginSubmit(event) {
event.preventDefault();
loginForm.classList.add(HIDDEN_CLASSNAME);
const username = logininput.value;
localStorage.setItem(USERNAME_KEY, username);
paintGreetings(username);
}
function paintGreetings(username) {
greeting.innerText = `Hello ${username}`;
greeting.classList.remove(HIDDEN_CLASSNAME);
}
const savedUsername = localStorage.getItem(USERNAME_KEY);
if (savedUsername === null) {
// show the form
loginForm.classList.remove(HIDDEN_CLASSNAME);
loginForm.addEventListener("submit", onLoginSubmit);
} else {
// show the greeting
paintGreetings(savedUsername);
}
' 노마드 코드 - 바닐라 JS로 크롬 앱 만들기' 공부하면서 정리한 내용입니다.