-
[노마드 코더] 바닐라 JS로 크롬 앱 만들기프론트엔드 개발자가 될거야./js 2022. 6. 19. 18:03
listen하고 싶은 event를 찾는 가장 좋은 방법
console.dir(h1);
메소드 & element의 내부를 볼 수 있음.
이벤트도 알 수 있음. -> on만 빼면 됨
className, classList, toggle의 사용 (feat. css는 css에서!)
- className의 버그 : 이전의 class들은 상관하지 않고 모든걸 교체해버림 => 이것을 해결한 것이 classList
- classList => clsaaList의 코드를 한 줄로 해결한 것이 toggle
// css .clicked { color: red; }
// JS if(h1.classList.contains("clicked")) { h1.classList.remove("clicked"); } else { h1.classList.add("clicked"); }
- toggle : classList에 clicked가 있는지 확인해서 있다면 제거, 없다면 추가
// JS h1.classList.toggle("clicked"); // classList에 clicked가 있는지 확인해서 있다면 제거, 없다면 추가
username 유효성 검사 (feat. input을 form안에 넣자.)
<form class="hidden" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> <button>Log In</button> </form>
input을 form안에 넣고 input의 속성으로 required, maxlength가 도와줘서 따로 js로 만들어 줄 필요가 없다.
방금 실핼된 이벤트 정보보기
// js console.log(event);
event의 기본동작 막기
예를들어, submit이벤트 실행 시 새로고침되는 기본동작
// js event.preventDefault();
String + 변수
방법2 사용하는 것이 더 유용
// 방법1 "Hello " + 변수명 // 방법2 `Hello ${변수명}`
localStorage에 username 저장하기
localStorage API = 미니DB
// 정보등록 localStorage.setItem("username", username); // 정보받기 : key에 해당하는 value를 String으로 받고 해당 value가 없으면 null로 받아옴 localStorage.getItem("username");
함수에서 String 반복할 경우, 변수 선언해주기
함수에서 String 반복할 경우, 실수 확률 높고 오류도 찾기 어렵다.
그래서 대문자로 변수를 선언해준다.
const USERNAME_KEY = "username"; const HIDDEN_CLASSNAME = "hidden";
CLOCK
const clock = document.querySelector("#clock"); function getClock() { const date = new Date(); const hours = String(date.getHours()).padStart(2,"0"); const minutes = String(date.getMinutes()).padStart(2,"0"); const seconds = String(date.getSeconds()).padStart(2,"0"); clock.innerText = `${hours}:${minutes}:${seconds}`; } getClock(); setInterval(getClock, 1000);
현재시간
const date = new Date();웹 사이트 load되자마자 (1초도 안기다리고 ) 바로 시간 보게하기
getClock();
setInterval(getClock, 1000);숫자 표기 방식 (1, 2, 3, 4 ---> 1초, 2초, 3초, 4초)=> String 문자 두 개로 채우기 = 최소 2개의 문자를 가지고 있어야 함"1".padStart(2, "0") // String의 길이를 2로 만다는데 그 길이가 2가 아니라면 앞에 0을 추가Number -> StringString(number)
QUOTE
Math.random()
: 0 ~ 1 사이의 실수 제공
-> 0 ~ 10 사이의 실수가 필요하다면
Math.random() * 10
반올림 Math.round()
올림 Math.ceil()
내림 Math.floor()
BACKGROUND
const images = [ "0.jpeg", "1.jpeg", "2.jpeg" ]; const chosenImage = images[Math.floor(Math.random() * images.length)] const bgImage = document.createElement("img"); bgImage.src = `img/${chosenImage}` document.body.appendChild(bgImage);
TODOLIST
// HTML <form id="todo-form"> <input type="text" placeholder="Write a To Do and Press Enter" required> </form> <ul id="todo-list"> // todo를 삭제하는 button을 만들거라 span사용 /* <li> <span>00하기</span> <button>❌</button> </li> */ </ul>
알아야 할 것 = localStorage는 String만 저장함
JSON.stringify()
: 배열, 객체 -> String 변경
JSON.stringify(배열,객체)
JSON.parse()
: String -> 배열 변경
JSON.parse(string)
Array.forEach(함수)
배열이 가지고 있는 각각의 item에게 함수를 실행해줌
function sayHello(item) { console.log("this is", item); } array.forEach(sayHello); // 처리되고 있는 item이 어떤 item인지 알 수 있음
Date.now()
: 1000만 분의 1의 확률로 랜덤숫자으로 줌
filter()
: true인 값만 저장하여 새로운 배열 생성가능
filter(todo => todo.text !== "lololo")
WEATHER
const API_KEY = "d631a7898756da95ef89715c54deade5"; function onGeoOk(position) { const lat = position.coords.latitude; const lon = position.coords.longitude; const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`; fetch(url) .then(response => response.json()) .then(data => { const weather = document.querySelector("#weather span:first-child"); const city = document.querySelector("#weather span:last-child"); city.innerText = data.name; weather.innerText = `${data.weather[0].main} / ${data.main.temp}` }); } function onGeoError() { alert("너의 날씨를 찾을 수 없습니다.") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
'프론트엔드 개발자가 될거야. > js' 카테고리의 다른 글
[TIL] Today I Learned : 수학표현식, 논리연산자, 가위 바위 보 게임 함수 만들기(rockPaperScissors 함수) (0) 2022.06.23 [TIL] Today I Learned : for문 - findSmallestElement 함수 (0) 2022.06.22 JS함수 정리 - 화살표함수, 즉시실행함수, 호이스팅, 타이머함수, 콜백 (0) 2022.06.14 자바스크립트 라이브러리 정리 (0) 2022.06.13 나의 첫번째 웹사이트 수정편 (0) 2022.06.13