๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript/Vanilla JS

[๋ฐ”๋‹๋ผJS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ] Saving the User Name part Two

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 26.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜-์œ ํŠœ๋ธŒ ๋…ธ๋งˆ๋“œ ์ฝ”๋” Nomad Coders]

https://youtu.be/7gYwj8vh_OQ

 

greeting.js

const form = document.querySelector(".js-form"),
    input = form.querySelector("input"),
    greeting = document.querySelector(".js-greetings");

const USER_LS = "currentUser",
    SHOWING_CN = "showing";

function handleSubmit(event){
    event.preventDefault();
    const currentValue = input.value;
    paintGreeting(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){
        askForName();
    } else {
        paintGreeting(currentUser);
    }
}

function init(){
    loadName();
}

init();

 

 

 

-์‚ฌ์šฉ์ž ์ €์žฅํ•˜๊ธฐ

function saveName(text){
    localStorage.setItem(USER_LS, text);
}
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){
        askForName();
    } else {
        paintGreeting(currentUser);
    }
}

function init(){
    loadName();
}

init();

์ƒˆ๋กœ๊ณ ์นจ ํ•ด๋„ ๊ทธ๋Œ€๋กœ์ž„.

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€