JavaScript - Saving the USer Name
HTML - class form input placeholder
-
class
-
form
-
input
-
placeholder
JavaScript - querySelector()
- querySelector
- gets the first element they found
- querySelectorAll
- gets all elements by array
- getElementById
- get element by tag name (ex : input, body, html, div, section)
JavaScript - classList
- classList
local storage
- ctrl + shift + J : javascript 코드 console, memory등을 확인 가능
-
Application - Local Storage : 자바스크립트 정보 저장 공간
- Console 창에서 아래와같이 localStorage값을 변경가능
localStorage.setItem("MG", true);
localStorage.getItme("MG");
Storage Name Project
- HTML code
<!DOCTYPE html>
<html>
<head>
<title>ClockChallenge</title>
<link rel="stylesheet" href="index.css"/>
</head>
<body>
<h2>Time Until Christmas</h2>
<div class="js-clock">
<h3>00d 00h 00m 00s</h3>
</div>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
<script src="clock.js"></script>
<script src="greeting.js"></script>
</body>
</html>
- CSS
body {
background-color: seashell;
}
h1 {
color: black;
}
.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_ON = "showing";
function saveName(text) {
localStorage.setItem(USER_LS, text);
}
function paintGreeting(text) {
form.classList.remove(SHOWING_ON);
greeting.classList.add(SHOWING_ON);
greeting.innerText = `Hello ${text}`;
}
function handleSubtmit(event) {
// prevent default event
event.preventDefault();
const currentValue = input.value;
paintGreeting(currentValue);
saveName(currentValue);
}
function askForName() {
form.classList.add(SHOWING_ON);
form.addEventListener("submit", handleSubtmit);
}
function loadName() {
const currentUser = localStorage.getItem(USER_LS);
if(currentUSer === null) { //if currentUser is under localStorage
// she is not
}
else {
// she is
paintGreeting(currentUser);
}
}
function init() {
loadName();
}
init();