728x90
참고자료: 노마드 코더 바닐라 JS로 크롬 앱 만들기 https://nomadcoders.co/javascript-for-beginners/lobby
1. Form Submission
<!DOCTYPE html>
<html lang="en">
<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">
<title>Momentum App</title>
</head>
<body>
<form id="login-form">
<input required maxlength="15" type="text" placeholder="What is your name?"/>
<button>Log In</button>
</div>
<script src="app.js"></script>
</body>
</html>
👉🏻HTML의 input 속성을 잘 활용하면 JS 없이 유효성 검사 로직을 만들 수 있다.
- required: 빈 값을 제출하지 못 하게 막는다.
- maxlength: input값의 최대 길이를 정해준다.
2-3. Events part One-Two
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");
const link = document.querySelector("a");
function onLoginSubmit(event) {
event.preventDefault;
}
function handleLinkClick(event) {
event.preventDefault;
}
loginForm.addEventListener("submit", onLoginSubmit);
link.addEventListener("click", handleLinkClick);
👉🏻JS는 함수를 호출할 때 궅이 지정하지 않아도 지금 막 벌어진 event에 대한 정보를 첫 번째 인자로 전달한다.
- click 이벤트는 mouseEvent를 전달해주고 그 안에는 클릭한 위치에 대한 정보도 담고 있다.
✍🏻preventDefault: 브라우저의 기본동작을 막아준다.
4. Getting Username
HTML
<!DOCTYPE html>
<html lang="en">
<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">
<title>Momentum App</title>
</head>
<body>
<form id="login-form">
<input required maxlength="15" type="text" placeholder="What is your name?"/>
<button>Log In</button>
</form>
<h1 id="greeting" class="hidden"></h1>
<script src="app.js"></script>
</body>
</html>
CSS
.hidden {
display: none;
}
JS
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");
const greeting = document.querySelector("#greeting");
const HIDDEN_CLASSNAME = "hidden";
function onLoginSubmit(event) {
event.preventDefault;
loginForm.classList.add(HIDDEN_CLASSNAME);
const username = loginInput.value;
greeting.innerText = `Hello ${username}`;
greeting.classList.remove(HIDDEN_CLASSNAME);
}
loginForm.addEventListener("submit", onLoginSubmit);
👉🏻단순히 문자열을 저장하는 변수를 정의할 때는 HIDDEN_CLASSNAME과 같이 전부 대문자로 적는 것이 관습이다.
👉🏻변수와 문자열을 함께 조합할 때는 백틱(`)과 달러 기호($)를 함께 쓴다.
5. Saving Username
localStorage.setItem("username", username);
👉🏻setItem: 브라우저 내장 db에 키와 값을 저장한다.
6. Loading Username
function paintGreeting(username) {
greeting.classList.remove(HIDDEN_CLASSNAME);
greeting.innerText = `Hello ${username}`;
}
const savedUsername = localStorage.getItem(USERNAME_KEY);
if (savedUsername === null) {
loginForm.classList.remove(HIDDEN_CLASSNAME);
loginForm.addEventListener("submit", onLoginSubmit);
} else {
paintGreeting(savedUsername);
}
👉🏻getItem: 브라우저 내장 db에서 값을 꺼내온다.
👉🏻꺼내온 username이 null값이라면 login form을 보여주고 그렇지 않다면 인사를 건네는 함수를 실행한다.
728x90