크롬앱 #3

^^* ,,·2022년 4월 6일
0

3 JAVASCRIPT ON THE BROWSER

3.0 The Document Object

3.1 HTML in Javascript

  • js 에서 html에 접근 by document.
  • ocument.getElementById(“title”) : html에 있는 id가 "title" 인 것 보기.
const title = document.getElementById("title");
console.dir("title");

  • js에서는 html이 표현하는 object를 보여줌.
  • js에서 html obj 내용 변경
title.innerText = “got you”
console.log(title.id);
console.log(title.calssName);
  • id로 접근하고 class 네임 확인

  • title id를 사용했기 때문에 (.)으로 접근이 가능했다.
  • 모든 것들을 html에서 항목들을 가지고와서 js에서 변경한다

3.2 Searching For Elements

  • innterText 등의 null 에러 -> 해당 id or className이 없음.
const hellos = document.getElementsByClassName("hello");
hellos.(으로 접근 가능)
  • className이 "hello"인 것들을 array로 반환

const title = document.getElementsByTagName("hi"); (모든 hi 태그를 array로 가져옴. )
console.log(title); 

const title = document.querySelector("hi"); 
console.log(title); 
  • querySelector : element를 CSS selector 방식으로 검색할 수 있음 (ex. h1:first-child)

const title = document.querySelector(".hello h1"); 
console.log(title); 
  • class hello를 찾고, 그 안의 h1 태그
  • 클래스 네임과 그 안의 태그를 명시해줘야 함
  • 하나의 element 리턴
  • 여러 항목이 있다면 첫번째 것 하나만 나옴

const title = document.querySelectorAll(".hello h1"); 
console.log(title); 
  • array로 다 가져옴.

  • id를 통해서 찾으려면 -> querySelector("#hello");
  • getElementById("hello"); 는 같은 일을 하는 것임
  • but 후자는 하위요소 가져오는 것을 못하므로 전자 주로 사용
  • (".~")
  • ("#~")

3.3 Events

  • element의 내부를 보고 싶으면 console.dir()
  • 기본적으로 object로 표시한 element를 보여줌(전부 js object임)
const title = document.querySelector("div.hello:first-child h1");
console.dir(title);
title.sytle.color="blue";

  • element 중 앞에 on이 붙은 것들은 event
  • event: 어떤 행위를 하는 것, 클릭 --> 모든 event는 js가 listen할 수 있음
  • eventListener : event를 listen함 → js에게 무슨 event를 listen하고 싶은 지 알려줘야 함
  • title.addEventListener("click") : 누군가가 title을 click하는 것을 listen할 거임 → 무언가를 해줘야함
const title = document.querySelector("div.hello:first-child h1");

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

title.addEventListener("click",handleTitleClick // 여기 괄호가 들어가면 안 된다.);
  • function이 js에게 넘겨주고 유저가 title을 click할 경우에 js가 실행버튼을 대신 눌러주길 바라는 것임( 직접 handleTitleClick(); 이렇게 하는 것이 아니라)
  • 함수에서 () 이 두 괄호를 추가함으로써 실행버튼을 누를 수 있는 거임

3.4 Events part Two

이벤트 처치하기

  • 구글에 찾고 싶은 element의 이름, 예를들어 h1 html element mdn을 검색.
  • 링크에 Web APIs라는 문장이 포함된 페이지를 찾가. (JS관점의 HTML Heading Element)
  • element를 console.dir로 출력해서 on~ 이라고 적혀있는걸 사용하면 됨.

function handleMouseEnter() {
title.innerText = "Mouse is here!"
}

function handleMouseLeave() {
title.innerText = "Mouse is gone!"
}

title.addEventListener("mouseenter", handleMouseEnter);
title.addEventListener("mouseleave", handleMouseLeave);


3.5 More Events

title.onclick = handleMouseEnter;
title.addEventListener(“mouseenter” , handleMouseEnter);

위에 두 코드는 동일하나 addEventListener를 선호하는 이유는
removeEventListener을 통해서 event listener을 제거할수있기 때문이다.


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


window는 기본제공

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

function handleWindowCopy(){
alert(“copier”);
}

window.addEventListener(“resize”, handleWindowResize);
window.addEventListener(“copy”, handleWindowCopy);
  • document의 body,head,title 이런것들은 중요하기 때문에 / document.body.style~의 명령이 허용되지만, div같은것들은 호출이 안됨
  • 나머지 element들은 querySelector나 getElementById로 불러와야.

3.6 CSS in Javascript

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

function handleTitleClick() {
    if (h1.sytle.color === "blue") {
        h1.sytle.color = "tomato";
    } else {
        h1.sytle.color="blue";
    }
}

h1.addEventListener("click", handleTitleClick);

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

function handleTitleClick() {

    const currentClolr = h1.sytle.color;
    let newColor;

    if (currentClolr === "blue") {
        newColor = "tomato";
    } else {
        newColor="blue";
    }
    
    h1.sytle.color = newColor;
}

h1.addEventListener("click", handleTitleClick);

=== 값이 일치함.
= color를 바꿔줌.


  • CSS는 JS파일에서도 할 수 있지만 sytle은 CSS에서 하는걸 선호한다.

  1. step1. element를 찾아라.
  2. step2. event를 listen해라.
  3. step3. 그 event에 반응해라.


3.7 CSS in Javascript part Two

1) HTML파일은 CSS문서와 JS문서를 임포트 하고있음.
2) CSS에 .active라는 class를 생성해주고
3) addEventListener로 h1을 클릭하면 handleTitleClick 함수가 작동
4) handleTitleClick 함수는 h1의 class name을 "active" 로 바꿈
5) .active의 color는 토마토색이기 때문에 토마토 색이 됨

css

body {
    background-color: beige;
}
h1 {
    color:cornflowerblue;
    transition:color 0.5s ease-in-out;
}

.active {
    color: tomato;
}


js

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

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

h1.addEventListener("click", handleTitleClick);

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

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

h1.addEventListener("click", handleTitleClick);

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

function handleTitleClick() {
    const clickedClass = "clicked";
    //오류를 쉽게 발견, 줄이는 방법. const에 저장. 
  
    if(h1.className === "clickedClass") {
        h1.className = "";
    } else {
        h1.className = "clickedClass";
    }
    
}

h1.addEventListener("click", handleTitleClick);
  1. style에 적합한 도구는 CSS, animation에 적합한 도구는 JS 이다
  2. raw string이 반복되면 const로 만들어 준다

3.8 CSS in Javascript part Three (toggle)

  • classList 우리가 class들의 목록으로 작업할수 있게끔 허용해준다.
  • className은 이전calss를 상관하지않고 모든걸 교체해 버린다.

classList를 이용하는건
js에서 건드리는건 HTML element가 가지고있는 또하나의 요소 사용하는 것이다.
= element의 class내용물을 조작하는 것을 허용한다는 뜻

  • contains은 우리가 명시한 class가 HTML element의 class에 포함되어 있는지 말해준다
//특정한 클래스만 추가, 제거
const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick() {
    const clickedClass = "clicked";

    if(h1.classList.contains(clickedClass)) {
        h1.classList.remove(clickedClass);
    } else {
        h1.classList.add(clickedClass);
    }
    
}

h1.addEventListener("click", handleTitleClick);

  • toggle function --> class name이 존재 유무 확인

toggle은 토큰이 존재하면 토큰제거
토큰존재 하지않으면 토큰 추가

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

function handleTitleClick() {
    h1.classList.toggle("clicked");
}

h1.addEventListener("click", handleTitleClick);
  1. toggle은 h1의 classList에 clicked class가 이미있는지 확인하여
  2. 만약있다면 toggle 이 clicked를 제거해준다
  3. class name이 존재하지 않는다면 toggle은 classname 추가

0개의 댓글