JavaScript challenge [5]

Date:

카테고리:

태그:

JavaScript interactive HTML

  1. HTML을 작성 한 다음
  2. JS로 interactive하게 만들어주자

HTML 작성

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Momentum App</title>
  </head>
  <body>
    <form id="login-form">
      <input
        required
        maxlength="15"
        type="text"
        placeholder="What is your name?"
      />
      <input type="submit" value="Log In" />
    </form>
    <script src="app.js"></script>
  </body>
</html>

JavaScript 작성

// input, button 가져오기
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");

// click Event
function onLoginSubmit(event) {
  // same as button

  // Arguments
  event.preventDefault();

  // input data == loginInput.value
  const username = loginInput.value;

  //   if (username === "") {
  //     alert("Please write your name");
  //   } else if (username.length > 15) {
  //     alert("Your name is too long.");
  //   }

  //  Just for check
  console.log(username);
}
loginForm.addEventListener("submit", onLoginSubmit);

설명

  1. logInput.value는 input 값을 의미한다.
  2. querySelector를 사용시에는 tag, id 등을 명확히 작성해야한다.
  3. ~.length는 ~의 string 길이를 보여준다 (python - len(~))
  4. 현재 이 코드를 따르면 HTML form에서 적용하는게 더욱 안정적이다.(advantage)
  5. input안에 있는 button이나, form을 submit하는 button은 기본적으로 새로고침을 한다. 이를 방지하기 위해서는 event.preventDefault()를 사용하면 된다. (브라우저 기본 동작을 정지한다.)
  6. Submit은 Enter를 누르거나 button을 누를때 적용된다.

JavaScript in HTML

  1. HTML을 작성 한 다음
  2. JS로 interactive하게 만들어주자

HTML 작성

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Momentum App</title>
  </head>
  <body>
    <form id="login-form">
      <input
        required
        maxlength="15"
        type="text"
        placeholder="What is your name?"
      />
      <input type="submit" value="Log In" />
    </form>
    <a href="https://nomadcoders.co"> Go to courses</a>
    <script src="app.js"></script>
  </body>
</html>


JavaScript 작성

// input, button 가져오기
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");

const link = document.querySelector("a");
// click Event
function onLoginSubmit(event) {
  // same as button

  // Arguments
  event.preventDefault();

  // input data == loginInput.value
  const username = loginInput.value;

  //   if (username === "") {
  //     alert("Please write your name");
  //   } else if (username.length > 15) {
  //     alert("Your name is too long.");
  //   }

  //  Just for check
  console.log(username);
}

function handleLinkClick(event) {
  event.preventDefault();
}
loginForm.addEventListener("submit", onLoginSubmit);
link.addEventListener("click", handleLinkClick);


설명 ( 1편에 이어서..)

  1. link 내 function은 직접 사용하지 않게 한다
  2. 브라우저는 link를 누르면 바로 창을 전환시킨다
  3. preventDefault로 브라우저의 작동을 금지시킨다.

JavaScript in HTML

  1. HTML을 작성 한 다음
  2. JS로 interactive하게 만들어주자

HTML 작성

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Momentum App</title>
  </head>
  <body>
    <form id="login-form">
      <input
        required
        maxlength="15"
        type="text"
        placeholder="What is your name?"
      />
      <input type="submit" value="Log In" />
    </form>
    <h1 id="greeting" class="'hidden"></h1>
    <a href="https://nomadcoders.co"> Go to courses</a>
    <script src="app.js"></script>
  </body>
</html>

E# JavaScript 작성

// input, button 가져오기
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");

const link = document.querySelector("a");

const greeting = document.querySelector("#greeting");
const HIDDEN_CLASSNAME = "hidden";
// click Event
function onLoginSubmit(event) {
  // same as button

  // Arguments
  event.preventDefault();

  // input data == loginInput.value
  const username = loginInput.value;

  //   if (username === "") {
  //     alert("Please write your name");
  //   } else if (username.length > 15) {
  //     alert("Your name is too long.");
  //   }

  //  Just for check
  console.log(username);
}

function handleLinkClick(event) {
  event.preventDefault();
  loginForm.classList.add(HIDDEN_CLASSNAME);
  const username = loginInput.value;
  //  loginForm 에 hidden class 부여
  // greeting.innerText = "Hello " + username;
  greeting.innerText = `Hello ${username}`;
  geeeting.classList.remove(HIDDEN_CLASSNAME);
}
loginForm.addEventListener("submit", onLoginSubmit);
link.addEventListener("click", handleLinkClick);
.hidden {
  /* display : None : 할당된 공간 자체를 삭제 */
  display: none;
}

설명 ( 1편에 이어서..)

  1. HIDDEN_CLASSNAME 은 CSS의 display: none 과 연결되어 브라우저에서 숨겨준다
  2. classList 는 attribute option을 추가한다
  3. python f string처럼 JS에서는 ~${variable} 처럼 사용이 가능하다

JavaScript, Document localStorage

  1. HTML을 작성 한 다음
  2. JS로 interactive하게 만들어주자

HTML 작성

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Momentum App</title>
  </head>
  <body>
    <form id="login-form">
      <input
        required
        maxlength="15"
        type="text"
        placeholder="What is your name?"
      />
      <input type="submit" value="Log In" />
    </form>
    <h1 id="greeting" class="'hidden"></h1>
    <a href="https://nomadcoders.co"> Go to courses</a>
    <script src="app.js"></script>
  </body>
</html>

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", username);
  localStorage.setItem(USERNAME_KEY, username);
  paintGreetings(username);
}

function paintGreetings(username) {
  greeting.innerText = `Hello ${username}`;
  greeting.classList.remove(HIDDEN_CLASSNAME);
}

loginForm.addEventListener("submit", onLoginSubmit);
const savedUsername = localStorage.getItem(USERNAME_KEY);

if (savedUsername === null) {
  loginForm.classList.remove(HIDDEN_CLASSNAME);
  loginForm.addEventListener("submit", onLoginSubmit);
} else {
  paintGreetings(savedUsername)}
.hidden {
  /* display : None : 할당된 공간 자체를 삭제 */
  display: none;
}

설명 ( 1편에 이어서..)

  1. localStorage (저장소)
  2. localStorage.setItem(“key”, “value”); 와 같은 코드로 저장한다.
  3. localStorage.removeItem(“key”); 와 같은 코드로 삭제한다.

JS 카테고리 내 다른 글 보러가기

댓글 남기기