20191107. 시계,이름설정 웹사이트, js부분
const form = document.querySelector(".js-form"),
input = form.querySelector("input"),
greeting = document.querySelector(".js-greetings");
/* html에서 js로 다룰 class들을 js에서 변수로 설정해놓자.
const를 사용해, 세가지 변수를 만들었다. */
그다음 이름을 불러오는 함수를 만든다, 변수설정으로 현재 로컬스토리지에 유저네임을 저장하고
저장된 변수가 이름이 설정되있을경우 showing 클래스로 바꾸어 보여지게하고, Hello문구를 붙인다.
저장된 변수가 이름이 설정되어있지않을 경우 askForName() 함수를 실행시키자.
function loadName(){
const currentUser = localStorage.getItem(USER_LS);
if (currentUser === null){
askForName();
} else {
paintGreeting(currentUser);
}
}
/* 첫번째 현재 유저이름 변수를 설정하고 localStorage.getItem으로 USER_LS를 불러오는데
USER_LS의 변수설정을 안해놨기때문에 우선해준다. */
const USER_LS ="currentUser",
SHOWING_CN = "showing";
/* 처음 USER_LS의 변수는 currentUser이다. 그리고 나중에 클래스 변경을 하기위해 showing변수도
만들어 놓는다. */
/* 다시 돌아가서 처음 USER_LS은 currentUser이며, if문을 만들어서 두가지 선택경로를 만든다.
처음에 currentUser는 null이다. 왜냐하면 localStorage.getItem(USER_LS); - 이것은 로컬스토리지의 currentUser(=USER_LS)의 value를 불러오는건데 currentUser의 초기 value값은 null이다. */
function askForName(){
form.classList.add(SHOWING_CN);
form.addEventListener("submit", handleSumit);
/* 그리고나서 이름을 적는 부분을 보여주게하고 submit할때 이벤트를 default 시키고 input의 value값을 저장시키는 함수를 만들어준다. form.classList.add(SHOWING_CN); 을 통해 input박스가 원래 css로 display:none; 되어있지만 showing 을 추가시켜 보여지게 한다. 그후에 form.addEventListener("submit", handleSumit); - 이것은 form태그가 submit 됬을시에 handleSubmit 함수를 실행하게 하는 문구이다. */
function handleSubmit(event){
event.preventDefault();
const currentValue = input.value;
paintGreeting(currentValue);
saveName(currentValue);
}
/* 이름을 적었을때 handleSubmit 함수는 발동된다. event라는 파라미터는 submit이라고 볼수있다. 즉 submit.preventDefault(); 가 실행되고 이 문구는 submit를 실행했을때 사라지는 것을 초기화시킨다.
const currentValue = input.value; 그리고 currentValue변수로 input의 value 값을 저장한다.
paintGreeting(currentValue); - 이름을 적은 value값을 paintGreeting 함수로 보내준다. 이 함수는 input class showing을 지우고 인사말 h4태그를 showing 하게 하며 그안에 텍스트를 삽입하여 인사말을 출력한다.
saveName(currentValue); - saveName 함수는 브라우저의 로컬스토리지에 영구적으로 저장하기위해서 실행한다. */
function saveName(text){
localStorage.setItem(USER_LS, text);
}
// localStorage.setItem(USER_LS, text); - USER_LS 에 text(=currentValue)를 입력받아 USER_LS라는 변수에 vlaue값을 저장해준다.
function paintGreeting(text){
form.classList.remove(SHOWING_CN);
greeting.classList.add(SHOWING_CN);
greeting.innerText = `Hello ${text}`;
}
/* 마지막으로 인사말 함수이다. 우선 form.classList.remove(SHOWING_CN); - input창의 class showing 을 지워준다.
greeting.classList.add(SHOWING_CN); - 인사말 태그 h4의 class 에 showing 을 추가하여 보여준다.
greeting.innerText = `Hello ${text}`; 함수파라미터로 받아온 text를 argument text에 넣어 Hello name을 출력시킨다. */
출처는 아카데미 니콜라스 강사의 수업