본문 바로가기
프로그래밍

wecode 사전스터디(7/20) 로그 - 2 (노마드코더 리뷰)

by Youngbin Kwon 2020. 7. 20.

위코드 개강(8/17) D-28.

 

배운 것/개발한 것

 노마드코더 JS 강의 : 강의 끝내기 + 코드 리뷰 글 올리기 - 2 (링크)


1. #3.2 Saving the User name (Part 1)

1) html 코드 (일부)

   <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="clock.js"></script>
    <script src="gretting.js"></script>
</body>
  • form 문과 form 내부의 input창 추가
  • greeting.js 파일 연결문 추가

2) CSS 코드 (일부)

.form,
.greetings {
  display: none;
}

.showing {
  display: block;
}
  • .form, .greetings의 display가 none인 이유 : 브라우저의 currentUser 명이 저장되어 있지 않을 경우(null) 이름을 입력하는 창인 .form과 이름이 표기되는 greeting의 display를 안보이게 설정 (*다음 파트에서 설명)
  • .showing의 display가 block인 이유 : 하단 JS 파일의 몇몇 태그에 .showing 클래스가 추가되게 되면 해당 태그가 html에서 보여지도록 수정하기 위함

3) JS 코드

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

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

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
  } else {
    paintGreeting(currentUser);
  }
}

function init() {
  loadName();
}

init();
  • form, input, greeting에 querySelector를 통해 해당 태그 선택
  • loadName 내 localStorage.getItem 기능 통해 현재 브라우저에 저장된 USER_LS 정보 가져오기 (참조)
  • paintGretting(text) : classList.remove와 add 통해 해당 태그 내 클래스 생성/삭제 (참조)

2. #3.3 Saving the User name (Part 2)

1) JS 코드 (일부)

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);
}
  • form 태그 내 신규 class showing을 추가하여, html 내의 form 태그를 표기 (.showing {display:block})
  • event.preventDefault (참조) : 해당 event의 기존 기능 실행 방지
  • input.value로 입력값을 받아온 후, 해당 value를 currentValue 인자로 paintGreeting 함수 실행
  • 이후 localStorage.setItem 기능을 통해 브라우저 내의 USER_LS 값 저장

(계속) 투두리스트 만들기

댓글