[바닐라 JS로 크롬 앱 만들기] 02 JavaScript on the Browser

박지원 ·2023년 2월 12일
post-thumbnail

1. The Document Object

자바스크립트에서는 HTML에 접근하고 읽을 수 있게 설정이 되어 있음.

document는 자바스크립트에서 HTML을 의미함.

자바스크립트는 HTML을 읽어오는 거임. 

브라우저가 HTML 정보가 아주 많이 들어있는 document라는 object를 전달해주는 것임.

근데 자바스크립트는 HTML을 읽어올 뿐만 아니라, HTML을 변경할 수도 있음.

자바스크립트가 HTML보다 property가 높음

2. HTML in JavaScript

<body>
    <h1 id ="title">Grab me!</h1>
    <script src="app.js"></script>
</body>

HTML에서 작성한 코드를 자바스크립트에서 가져올 수 있음.

자바스크립트 element에서 class name이 비어있는 것을 볼 수 있음.

<body>
    <h1 class="hello"  id ="title">Grab me!</h1>
    <script src="app.js"></script>
</body>

하지만 HTML에서 class name을 할당해준다면

자바스크립트에서 타이틀 innertext를 변경하면 HTML에서 건드리지 않아도 요소는 변경됨.
JS

HTML

결과 요소

정리하자면
1. JS에서 document(HTML code & element)를 읽어올 수 있고
2. JS에서 documnet내용을 변경할 수 있음

3. Events

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

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

title.addEventListener("click", handleTitleClick);

event요소찾기
on이 붙어있으면 event임

마우스 커서에 움직임으로 반응을 조절할 수 있음.
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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <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");

console.dir(title);
function handleTitleClick() {
    title.style.color = "blue";
}
function handleMouseEnter() {
    title.innerText = "Mosue is here";
}
function handleMouseLeave() {
    title.innerText = "Mosue is gone";
}
title.addEventListener("click", handleTitleClick);
title.addEventListener("mouseenter",handleMouseEnter);
title.addEventListener("mouseleave", handleMouseLeave);

JS(위와 같은 코드인데 이렇게 표현도 가능, 불호)

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

console.dir(title);
function handleTitleClick() {
    title.style.color = "blue";
}
function handleMouseEnter() {
    title.innerText = "Mosue is here";
}
function handleMouseLeave() {
    title.innerText = "Mosue is gone";
}
title.onclick = handleTitleClick;
title.onmouseenter = handleMouseEnter;
title.onmouseleave = handleMouseLeave;

더 추가적인 event

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

console.dir(title);
function handleTitleClick() {
    title.style.color = "blue";
}
function handleMouseEnter() {
    title.innerText = "Mosue is here";
}
function handleMouseLeave() {
    title.innerText = "Mosue is gone";
}
function handleWindowResize() {
    document.body.style.backgroundColor="tomato";
}
function handleWindowCopy() {
    alert("copier!");
}
function handleWindowOffline() {
    alert("sos no wifi");
}
function handleWindowOnline() {
    alert("Allgood");
}
title.onclick = handleTitleClick;
title.onmouseenter = handleMouseEnter;
title.onmouseleave = handleMouseLeave;

window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy", handleWindowCopy);
window.addEventListener("offline",handleWindowOffline);
window.addEventListener("online",handleWindowOnline)

클릭하면 색깔이 바뀌도록 만들기

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);

4 CSS in JS

자바스크립트에서 스타일을 바꾸는 건 별로 좋지 않음.
각 기능에 맞는 툴이 있는 것임.

만약 h1 안에 다른 class가 있는데 이 class를 유지하면서 h1을 유지하고 싶다면 classList를 사용해야함.
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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <div class="hello">
        <h1 class="sexy-font">Click me!</h1> 
    </div>
    <script src="app.js"></script>
</body>
</html>

CSS

body{
    background-color: beige;
}

h1 {
    color: cornflowerblue;
    transition:color .5s ease-in-out ;
}
.clicked {
    color: tomato;
}

JS(classList)

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이 존재하는지 확인하는 함수

그래서 JS 코드를 한 줄로 만들자면

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

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

toggle은 h1의 classList에 clicked class가 이미 있는지 확인해서 만약 있다면 toggle이 제거해줌, 만약 h1의 classList에 clicked가 존재하지 않는다면 toggle은 clicked를 classList에 넣을거임.

profile
배움이 즐거운 개발자

0개의 댓글