Links

Saving the User Name

이름 입력받고 저장하기

html

<section class="center">
<div class="js-clock clock">
<h3 class="clock__text">00:00</h3>
</div>
<div class="js-name name"></div>
<div>
<form class="js-to-do to-do">
<input class="js-add-to-do to-do__add-to-do" placeholder="Write a To Do here" type="text" />
</form>
<ul class="js-list list"></ul>
</div>
</section>
<div class="js-location location">
<span class="location__text"></span>
</div>
<div class="js-weather weather">
<span class="weather__text"></span>
</div>
<script src="js/clock.js"></script>
<script src="js/greeting.js"></script>
<script src="js/todo.js"></script>

javascript

const nameContainer = document.querySelector(".js-name"); // 이름이 나올 부분
function paintName(name) {
nameContainer.innerHTML = ""; // .js-name html을 쓸것을 선언
const title = document.createElement("span"); // .js-name 하위에 span 생성
title.className = "name__text"; //js-name 하위에 span에 name__text 클래스명 추가
title.innerHTML = `Hello ${name}`; // span 안에 Hello 입력될 이름이 입력되게한다.
nameContainer.appendChild(title); // nameContainer에 요소 추가한다.
}
function handleSubmit(event) {
event.preventDefault();
const form = event.target;
const input = form.querySelector("input"); // form -> input
const value = input.value; // input의 value값 저장
localStorage.setItem("username", value);
paintName(value);// 입력한값을 value 값으로 저장
}
function paintInput() {
const input = document.createElement("input");
input.placeholder = "Type your name here";
input.type = "text";
input.className = "name__input";
const form = document.createElement("form");
form.addEventListener("submit", handleSubmit);
form.appendChild(input);
nameContainer.appendChild(form);
}
function loadName() {
const name = localStorage.getItem("username");
if (name === null) {
paintInput();
} else {
paintName(name);// 이름을 입력받을때 출력
}
}
function init() {
loadName();
}
init();