📝
서은 STUDY_SCRIPT
  • JAVASCRIPT 기록
  • JAVASCRIPT 문법정리
    • 데이터 저장하기
    • 데이터 불러오기
    • 데이터 실행하기
    • 데이터 제어하기
    • 면접질문 정리
  • PHP를 이용한 사이트 작업
    • PHP와 MySQL
      • 댓글쓰기
      • 회원가입
      • 로그인
      • 게시판
        • 페이지네이션 & 게시글보기
        • 수정/삭제/목록/검색
  • 생활코딩 JavaScript
    • JavaScript 입문수업
      • Basic
        • 자바스크립트 기본 세팅
        • 데이터타입
        • 변수
        • 연산자
        • 조건문
        • 반복문
        • 함수
        • 배열
        • 객체
        • 모듈
        • 정규표현식
      • 함수지향
        • 유효범위
        • 값으로서 함수
        • 값으로서 콜백
        • 클로저
        • arguments
        • 함수의 호출
      • 객체지향
        • 생성자와 new
        • 전역객체
        • this
        • 상속
        • Prototype
        • 표준내장객체의 확장
        • Object
        • 데이터 타입
        • 복제 & 참조
    • JavaScript Basic
      • 자바스크립트란?
      • 데이터타입
      • 변수와 대입연산자
      • 제어할 태그 선택
      • 비교연산자와 불리언
      • 조건문 if
      • 리팩토링
      • 배열 [ ]
      • 반복문 while
      • 배열과 반복문
        • 배열과 반복문의 활용
      • 함수
        • 함수의 활용
      • 객체 { }
        • 객체와 반복문 for~in
        • 프로퍼티와 메소드
        • 객체의 활용
      • 파일로 쪼개서 정리정돈
      • 라이브러리 & 프레임워크
      • UI & API
    • Web Browser
      • JavaScript란?
      • BOM
        • 전역객체 window
        • 사용자와 커뮤니케이션
        • Location 객체
        • Navigator 객체
        • 창 제어
      • DOM
        • 제어 대상 찾기
        • jQuery
        • HTMLElement
        • Element 객체
          • 식별자 API
          • 조회 API
          • 속성 API
        • Node 객체
          • Node 관계 API
          • Node 종류 API
          • Node 변경 API
          • jQuery 노드 변경 API
          • 문자열로 노드 제어
        • HTMLCollection
      • 이벤트
        • 이벤트 등록
        • 이벤트 전파(버블링과 캡처링)
        • 이벤트 기본 동작 취소
        • 이벤트 타입
      • 네트워크 통신
        • Ajax
        • JSON
  • NOMAD JAVASCRIPT
    • VanillaJS
      • Why JS?
      • ES5, ES6
      • Basic
        • Alert & Console
        • Variable
        • Data Types
        • Array & Object
      • Function
      • DOM
        • Event & Event handler
        • Conditional
        • Function Practice
      • Momentum App
        • Making a JS Clock
        • Saving the User Name
        • To-Do List
        • Image Background
        • Getting Weather
  • DREAM CODING
    • 자바스크립트 기초 강의 (ES5+)
      • JavaScript 역사
      • async & defer / Strict Mode
      • Variable / Hoisting / Data Type
      • Operator / if / Loop
      • Function
        • 함수의 선언
        • 함수의 표현
      • Class
      • Object
      • Array
      • Array API
      • JSON
      • Callback
      • Promise
      • Async & Await
  • WEB BOS
    • #JavaScript30
Powered by GitBook
On this page

Was this helpful?

  1. NOMAD JAVASCRIPT
  2. VanillaJS
  3. Momentum App

Saving the User Name

2. 유저명 저장하기 : 입력된 유저명을 저장하여 화면에 출력

<!DOCTYPE html>
<html>
<head>
    <title>Something</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="js-clock">
        <div class="js-title">
            <h1>00:00</h1>
        </div>
    </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="greeting.js"></script>
</body>
</html>
body {
  color: #34495e;
}

.form,
.greetings {
  display: none;
}

.showing {
  display: block;
}
const form = document.querySelector(".js-form"),
    input = form.querySelector("input"),
    greeting = document.querySelector(".js-greetings");

const USER_LS = "currentUser", //LocalStorage
    SHOWING_CN = "showing";    //ClassName

function saveName(text){
    localStorage.setItem(USER_LS, text);
}

function handleSubmit(event){
    event.preventDefault();             //event의 기본값 삭제
    const currentValue = input.value;   //value 값 가져오기
    paintGreeting(currentValue);
    saveName(currentValue);
}

function askForName(){
    form.classList.add(SHOWING_CN);
    form.addEventListener("submit", handleSubmit);
}

function paintGreeting(text){
    form.classList.remove(SHOWING_CN); //유저 등록 되어있는 상태로 form을 숨겨줘야 함
    greeting.classList.add(SHOWING_CN);
    greeting.innerText = `Hello ${text}`;
}

function loadName(){
    const currentUser = localStorage.getItem(USER_LS); //LS에서 데이터가져오기
    if(currentUser === null){
        askForName();
    } else {
        paintGreeting(currentUser);
    }
}

function init(){
    loadName();
}

init();

LocalStorage : 작은 자바스크립트 정보들로서, 유저 브라우저에 저장됨

작업관리자 - Application - Local Storage

Null : 존재하지 않음을 의미 = undefined, cannot find

function(event){}

  1. 보통 event 발생하면 root에서 일어나고 form에서 일어남

  2. event는 일종의 거품 같은 것, 올라가면서 다른 모든 것들이 event에 반응하게 됨

  3. 즉, form을 제출하는 event가 발생하면 event가 document까지 올라감

  4. document는 프로그램 되어진 대로 다른 곳으로 감

  5. 페이지가 새로고침 됨

→ event의 기본값(기본동작)

event.preventDefault(); : event의 기본값을 막는 메소드

  • paintGreeting은 text를 필요로 함

  • submit : 제출

PreviousMaking a JS ClockNextTo-Do List

Last updated 3 years ago

Was this helpful?