본문 바로가기
언어/JS

[JS #3] 바닐라 JS로 크롬 앱 만들기

by 코딩맛집 2022. 11. 8.

# 3.2 Searching For Elements

<getElementById>

  • getElementById는 querySelector("#hello form")처럼 id=hello 하위에 있는 form을 가져오지 못한다.

<querySelector>

  • querySelector(".hello h1")은 class=hello에 h1이 여러개 있다면, 첫 번째 h1만 가져온다.

<querySelectorAll>

  • 다 보고 싶다면 querySelectorAll을 사용한다. querySelectorAll은 array를 반환해준다.

 

# 3.3 Event

js 파일이 있기 때문에 js를 통해서 html의 내용을 가져올 수 있다.

html이 js파일을 load하기 때문에 document가 존재한다. -> browser가 우리를 document에 접근할 수 있게 해준다.

 

 

- element의 내부를 보고 싶으면 console.dir()  <- js object들이 보인다. 그 중 on이 붙은 element는 event이다.
- event: 모든 event는 js가 listen할 수 있다.
- eventListener : event를 listen함 → js에게 무슨 event를 listen하고 싶은 지 알려줘야 함
- title.addEventListener("click") : 누군가가 title을 click하는 것을 listen한다. → function을 해줘야 한다.

 

<예시>
const title = document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
  title.style.color = "blue";
}
title.addEventListener("click",handleTitleClick);
//click하면 handleTitleClick이라는 function이 동작하길 원한다.

함수에서 () 이 두 괄호를 추가함으로써 실행버튼을 누를 수 있다.
//그래서 handle~ 함수에 () 를 안넣었다. ()를 넣으면 바로 실행하기 때문이다.
//즉, js가 대신 실행시켜주길 바라는 것임!

- function이 js에게 넘겨주고 유저가 title을 click할 경우에 js가 실행버튼을 대신 눌러주길 바라는 것이다.

( 직접 handleTitleClick(); 이렇게 하는 것이 아니라)

 

<예시 : 글씨의 색상을 랜덤으로 바꾸는 코드>

const title = document.querySelector("div h1");

function handleTitleClick(){
  const ranColor = ["blue","red","green","yellow","black"];

let num = Math.floor(Math.random() * ranColor.length);
title.style.color = ranColor[num];
}

title.addEventListener("click",handleTitleClick);

 

# 3.4 Event

< listen하고 싶은 event를 찾는 가장 좋은 방법 >

1. 예를들어, h1 html element mdn을 검색한다.
2. 링크에 Web APIs라는 문장이 포함된 페이지를 찾는다. (javascript 관점의  HTML Heading Element란 의미)

3. 너무 복잡하면 IDE에 element를 console.dir로 출력해서 on~ 이라고 적혀있는걸 사용하면 된다.

 

# 3.5 More Events

1. document에서 body,head,title 은 중요해서 언제든
    ex) document.body 로 가져올수있지만
2. div나 h1 등 element 들은 querySelector getElementById등으로 찾아야한다.
    ex) document.querySelector(“h1”);
3. window는 기본제공

    ex) window.addEventListener(“resize”, handleWindowResize);

 

# 3.6 CSS in Javascript

요즘 var 보다는 const(상수, 변하지 않는 값)과 let(변하는 값)으로 구분해서 사용한다고 합니다.

<예시>

const hi = document.querySelector(".hello h1");

function titleClick() {
  const currentColor = hi.style.color;
  let newColor;

  if (currentColor === "black") {
    newColor = "pink";
  } else {
    newColor = "black";
  }
  hi.style.color = newColor;
}

hi.addEventListener("click", titleClick);

 

!!!   hi.style.color = newColor; currentColor = hi.style.color; 로 쓰는 이유  !!!

newColor라는 빈 let변수를 선언했고 if, else를 거치면서 초기화 값을 할당받게 됩니다. 즉, newColor="pink"; 가 되죠! 이 값을 h1에 넣어주는 것이기 때문에 hi.style.color=newColor;가 됩니다.

 

# 3.7 CSS in Javascript part Two

style작업에 적합한 도구는 CSS, animation에 적합한 도구는 JS다.

html 파일은 CSS문서와 JS문서를 import하고 있다.
에러를 줄이기 위해 raw string을 쓰는 대신, const를 생성한다. 그래야 어디서 에러가 났는지 볼 수도 있다.
JS로 모든 class name을 변경하지는 않는다.

 

# 3.8 CSS in Javascript part Three

<예시>

const hi = document.querySelector(".hello h1");

function titleClick() {
  hi.classList.toggle("clicked");
}

hi.addEventListener("click", titleClick);
 
한 줄이면 끝나는 toggle,,,