๐Ÿ‘ฉ๐Ÿผโ€๐Ÿ’ป๋ฐ”๋‹๋ผ JS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ :#4.3-4.5

change upยท2023๋…„ 6์›” 8์ผ
2
post-custom-banner

1. output

Momentum Log In

2. 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">
    <link rel = "stylesheet" href="app.css">
    <title>Momentum</title>
</head>
<body>
    <form class="hidden" id="login-form">
    <input type="text" />
    <button id="button">Log In</button>
    <a href="https://nomadcoders.co/" class="hidden">Go nomad!</a>
    </form>
    <h1 id="greeting" class="hidden"></h1>
    <script src="app.js"></script>
</body>
</html>
<!---href๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์‚ฌ์ดํŠธ๋ฅผ ๊ฐ€์ ธ์˜ฌ์ˆ˜ ์žˆ๋„๋ก ์—ฐ๊ฒฐ์‹œ์ผœ์ค€๋‹ค.
hidden ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” html์˜ class hidden+ css์— hidden none display ์ถ”๊ฐ€ -->

3. JavaScript

const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");
const greeting = document.querySelector("#greeting");

const HIDDEN_CLASSNAME = "hidden"; 
const USERNAME_KEY = "username";
// ์ค‘๋ณต๋˜๋Š” ๊ฐ’์€ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•ด์ค˜์„œ ์‹ค์ˆ˜๋ฅผ ์ค„์ด๋„๋ก ํ•œ๋‹ค.
function onLoginSubmit(event) {
  event.preventDefault();
  loginForm.classList.add(HIDDEN_CLASSNAME);
  const username = loginInput.value;
  localStorage.setItem("USERNAME_KEY", username);
  paintGreetings(username);
}


function paintGreetings(username){
  greeting.innerText = `Hello ${username}`;
  greeting.classList.remove(HIDDEN_CLASSNAME);
  //value๊ฐ’์„ ๊ธฐ์–ตํ•ด์„œ ์•„์›ƒํ’‹ ํ•ด์ฃผ๊ณ  , ์ƒˆ๋กœ๊ณ ์นจ์„ ๋ˆ„๋ฅด๋ฉด ์ธ์‚ฌ๋ง์€ ์‚ฌ๋ผ๊ณ  ๋‹ค์‹œ ๋กœ๊ทธ์ธ์ฐฝ์ด ๋‚˜์˜จ๋‹ค.
}
//์ค‘๋ณต๋˜๋Š” ์‹์„ ์ œ๊ฑฐํ•˜๊ธฐ ์œ„ํ•ด , ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด์ฃผ๊ณ  ํ•จ์ˆ˜ํ˜ธ์ถœ ํ•˜๋Š” ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค.
//๊ฐ™์€ ํ•จ์ˆ˜๋ผ๋„ ํ˜ธ์ถœ๋˜๋Š” ์‹œ์ ์— ๋”ฐ๋ผ ๋งค๊ฐœ์ธ์ž๋Š” ๋‹ฌ๋ผ์ง„๋‹ค.
const savedUsername = localStorage.getItem("USERNAME_KEY");
console.log(savedUsername)// null ๊ฒฐ๊ณผ๊ฐ’
//logic์งœ๊ธฐ 
if(savedUsername === null){
 loginForm.classList.remove(HIDDEN_CLASSNAME);
 loginForm.addEventListener("submit",onLoginSubmit);
  //show the form
} else {
  paintGreetings(savedUsername)

}

//1.localStrage.setItem('mycat','tom)<- key .value local storage์— ์ •๋ณด๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋‹ค.
//2.local storage.remove('mycat') ์ €์žฅํ•œ ๋‚ด์šฉ์‚ญ์ œ ๊ฐ€๋Šฅ.
//3.localStorage.getItem("username") ์œ ์ €๋„ค์ž„ ๊ธฐ๋ก ์œ ๋ฌด ํ™•์ธ.

4. css

.hidden {
    display: none;
}
profile
์ƒˆ์‹น์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€