카테고리 없음

[Nomad/바닐라 JS Challenges] 4일차 | Ch03 JAVASCRIPT ON THE BROWSER

루이란 2022. 6. 10. 12:42
728x90

참고자료: 노마드 코더 바닐라 JS로 크롬 앱 만들기 https://nomadcoders.co/javascript-for-beginners/lobby

 

1.  HTML in Javascript


HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum App</title>
</head>
<body>
    <h1 class="hello" id="title">Grab me!</h1>
    <script src="app.js"></script>
</body>
</html>
JS
const title = document.getElementById('title');

title.innerText = "Got you!"

console.log(title.className)

👉🏻id 값으로 html 요소를 찾을 수 있다.

 

2.  Searching For Elements


const hellos = document.getElementsByClassName("Hello");
const hello = document.querySelector(".Hello");

title.innerText = "Got you!";

console.log(hellos);

👉🏻querySelectorquerySelectorAllcss 탐색 방식으로 element를 가져올 수 있다. 단 querySelector로 element를 찾으면 첫 번째 요소만 나온다.

 

3-4.  Events part One-Two


HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum App</title>
</head>
<body>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>
    <script src="app.js"></script>
</body>
</html>
JS
const title = document.querySelector("div.hello:first-child h1");

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

title.addEventListener("click", handleTitleClick)

👉🏻addEventListener로 이벤트를 추가할 수 있다. 첫 번째 인자가 이벤트를 수행시킬 동작(이벤트)이고 두 번째 인자가 이벤트 동작이다. 아래와 같이 다양한 이벤트들이 있다.

  • click
  • mouseenter
  • mouseleave
console.log(hellos);
console.dir(hellos);

💡console.dir을 사용하면 객체가 담은 정보를 다 볼 수 있다!

 

5.  More Events


👉🏻다양한 이벤트들을 알아보자!

  • resize: 윈도우 사이즈를 늘리거나 줄였을 때
  • copy: cntl+c를 눌렀을 때
  • online/offline: 와이파이를 켜거나 끌 때

 

코드 챌린지


👉🏻오늘 처음으로 퀴즈가 아닌 직접 코딩하는 과제가 나왔다. 배운 내용을 그대로 적으면 돼서 어렵지는 않았당!

 

728x90