본문 바로가기

Studying/Javascript

바닐라 JS로 크롬 앱 만들기 #3.0~#3.8

* JS에서 HTML을 읽어올 뿐만 아니라, 변경도 가능함

 

- JS에서 HTML 불러오는 법 : 

console에서 document 입력

-> JS는 HTML element를 가지고 오지만, HTML 그 자체를 보여주는 것이 아님.

*) document.body 만 가능

  document.div 등등은 불가능

 

 

- JS에서 HTML element 불러오는 법 : 

1. id로 부르기 : document.getElementById("title") 

2. class로 부르기 : document.getElementsByClassName("hello");

3. tag로 부르기 : document.getElementsByTagName("h1")

4. querySelector로 부르기 : document.querySelector(".title h1")

    = document.querySelectorAll(".title h1:first-child")

-> class title 내부에 존재하는 h1 부르기, title이라는 class를 가진 h1이 여러 개인 경우 첫 번째것만 값으로 나옴.

 *) document.querySelectorAll(".title h1"); 을 사용하면 selector 안의 조건에 부합하는 모든 element를 가져다줌.

 *) document.querySelector("#title h1") : id를 부르고 싶을 때 사용 

     = document.getElementById("title")

 

 

* console.dir()

JS의 object를 세세하게 보고 싶을 때 console.log()대신 사용함.

 

 

* Events

사용하는 법

title.onclick = handleTitleClick;    ==  title.addEventListener("click", handleTitleClick);

function handleTitleClick {
    console.log("title was clicked!");
}


title.addEventListener("click", handleTitleClick);

 

-> title이 click되었을 때, handleTitleClick이라는 function이 작동하길 원한다. 그래서  console.log("title was clicked!")가

작동하게 됨.

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


function handleTitleClick() {
    title.style.color = "blue";
}


title.addEventListener("click", handleTitleClick);

 

- click : 클릭한 상태

- mouseEnter : 마우스를 갖다댄 상태

- mouseLeave: 마우스가 벗어난 상태

- resize : window의 크기가 변경된 상태

예)

function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}

window.addEventListener("resize", handleWindowResize);

 

- copy : user가 copy 누른 경우

예)

function handleWindowCopy() {
alert("copier!");
}

window.addEventListener("copy", handleWindowCopy);

 

- offline : wifi 작동 안 할 때

- online : wifi이 다시 연결됐을 때

 

 

* CSS in JS

 

- 클릭할 때마다 색상을 바꾸는 법 

const h1 = document.querySelector("div.hello:first-child h1")

function handleTitleClick() {
    const currentColor = h1.style.color;
    let newColor;
    if(currentColor === "blue") {
        newColor = "tomato";
    }
    else {
        newColor = "blue";
    }
    h1.style.color = newColor;
}

h1.addEventListener("click", handleTitleClick)

-> h1의 색상이 blue라면, tomato로 바꾸고, blue가 아니라면 blue로 바꿔라

 

- js에서 h1에 active class를 전달하는 방법

const h1 = document.querySelector("div.hello:first-child h1")

function handleTitleClick() {
   h1.className = "active";
}

h1.addEventListener("click", handleTitleClick)

-> html 변경 없이 css에서만 .active { color: cornflowerblue; } 만 지정해놓고 js에서 상단 내용을 입력하면 

html까지 알아서 변경되는 효과가 생김.

 

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*