본문 바로가기

js

localStorage에 data 저장하고 불러오기

1. html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 id="title" class="btn">This works!</h1>
<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>

<script src="index.js"></script>
<script src="clock.js"></script>
<script src="greeting.js"></script>
</body>
</html>


2. css


body {
background-color: rgb(129, 156, 86);
color: white;
}

.clicked {
color: orange;
}

.btn {
cursor: pointer;
}

.form,
.greetings {
display: none;
}

.showing {
display: block;
}


3. JavaScript


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;
paintGreeting(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) {
// she is not
askForName();
} else {
// she is
paintGreeting(currentUser);
}
}

function init() {
loadName();
}

init();


4. result


1) 이름 입력 전


2) 이름 입력 후 localStorage에 data가 저장된 모습, 그리고 불러오는 모습 





'js' 카테고리의 다른 글

AJAX 란?  (0) 2019.04.07
make clock with vanilaJS  (0) 2018.12.29
간단한 function 만들기, MDN 문서의 중요성  (0) 2018.12.23
변수의 선언과 JS 자료 저장 구조(배열)  (0) 2018.12.23
Your first JS Function  (0) 2018.12.18