JavaScript
css style
- 스타일은 카멜 케이스로 작성한다.
- 혹은 대괄호 안에 속성을 지정한다.
- 여러 속성 또한 문자열로 작성한다.
className
또한 지정할 수 있다.- 클래스가 여러 개 존재할 수 있는데, 작성할 때마다 모든 클래스를 전부 작성해줘야 하기 때문에 잘 사용하지 않는다.
1
2
3
4
5
6
7
8
9
<div id="box"></div>;
const box = document.getElementId("div");
box.style.backgroundColor = "red";
box.style.width = "100px";
box.style.height = "100px";
box.style["margin-left"] = "100px";
box.style.border = "solid 1px black";
box.className = "box1";
- 이러한 불편함 때문에
classList
가 존재하는데, 메서드 중add
와remove
등을 이용하여 여러 개의 클래스를 추가하거나 삭제할 수 있다.
classList add, remove, replace
1
2
3
4
5
6
7
8
9
10
11
box.classList.add("box-red");
box.classList; // DOMTokenList ["box1", "box-red", value: "box1 box-red"]
box.classList.add("tem", "red-box");
box.classList; // DOMTokenList ["box1", "box-red", "tem", "red-box" value: "box1 box-red tem red-box"]
box.classList.remove("tem");
box.classList; // DOMTokenList ["box1", "box-red", "red-box" value: "box1 box-red red-box"]
box.classList.replace("box1", "box2");
box.classList; // DOMTokenList ["box2", "box-red", "red-box" value: "box2 box-red red-box"]
classList toggle
- 클래스가 있으면 제거하고 없으면 추가하는 기능을 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
setInterval(() => {
box.classList.toggle("box1");
},1000)
// 반복
// box.classList; // DOMTokenList ["box1", "box2", "box-red", "red-box" value: "box1 box2 box-red red-box"]
// box.classList; // DOMTokenList ["box2", "box-red", "red-box" value: "box2 box-red red-box"]
<ul id="color">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
const color = document.getElementById("color");
color.onClick = function(e){
const target = e.target;
if(target.tagName !== "LI") return;
target.classList.toggle("pink");
}
EVENT
- HTMLDOMEvent는 여러 가지 메서드를 갖고 있다.
- 이를
on
뒤에 붙는 이벤트에 따라 메서드를 실행시킬 수 있다.onClick, onMouseOver, onFoucus, onKeyDown...
addEventListener, removeEventListener
- 이벤트를 추가하거나 삭제할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<button id="click1" onClick="alert('click')">클릭</button>
<button id="click2" onClick="click()">클릭</button>
<button id="click3">클릭</button>
<button id="click4">클릭</button>
function click(){
alert('click');e
}
const btn = document.getElementById("click3");
btn.onClick = click;
const btn2 = document.getElementById("click4");
// btn2.addEventListener("click", click);
btn2.addEventListener("click", () => {
alert('click');
});
- 핸들러는 이벤트를 받는다.
1
2
3
4
5
6
7
8
9
<input id="txt" type="text" />;
const input = document.getElementById("input");
input.addEventListener("keyup", (event) => {
console.log(event, event.key);
});
// keyboadrdEvent {isTrusted: true, key: [입력된 키값], code: [입력된 키값의 코드, keyA, keyB 등]...}
// a
event
에는 다양한 메서드가 있기 때문에 한 번씩 찍어본다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="box" style="position: relative; width: 100px; height: 100px; border: solid 1px red">
<div id="circle" style="position: absolute; width: 10px; height: 10px; border-radius: 3px; background-color: black;"/>
</box>
const box = document.getElementById("box");
const circle = document.getElementById("circle")
box.addEventListener("mousemove", event => {
console.log(event);
// 다양한 메서드들 중 clientX, clientY 등 마우스의 좌표값
circle.style.top = `${event.clientX}`;
circle.style.left = `${event.clientY}`;
})
window.addEventLister("resize", event => {
document.body.innerText = `현재 창 크기는 ${window.innerWidth} x ${window.innerHeight} 입니다.`;
})
DOMContentLoaded
- 일부 이벤트를 처리할 때 사용되며, 문서가 로드되었을 때 실행된다.
1
2
3
document.addEventListener("DOMContentLoaded", () => {
document.body.style.backgroundColor = "red";
});
이벤트 버블링
- 자식 요소에서 발생한 이벤트 객체가 부모 요소에 전파되는 것을 말한다.
- 더 이상 부모 요소가 없을 때까지 이벤트 버블링이 발생한다.
- 대부분의 이벤트는 전파되지만
focus, blur, mouseenter, mouseleave
는 전파되지 않기 때문에, 만약 이 이벤트들이 발생했을 때, 상위 요소에서 이를 추적하려면focusin, focusout, mouseover, mouseout
등의 이벤트로 대체해주어야 한다. - 이벤트 버블링은 막을 수 있는데,
event
를 받아stopPropagation()
을 사용하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<div id="box">
<ul id="list">
<li id="color"></li>
</ul>
</div>;
const box = document.getElementById("box");
const list = document.getElementById("list");
const color = document.getElementById("color");
document.body.addEventListener("click", () => {
console.log("1, body");
});
box.addEventListener("click", () => {
console.log("2, div");
});
list.addEventListener("click", () => {
console.log("3, ul");
});
color.addEventListener("click", () => {
console.log("4, li");
});
// 이벤트 버블링
<div id="box">
<input id="txt"></input>
</div>;
box.addEventListener("focusin", () => {
console.log("1, div");
});
input.addEventListener("focusin", (event) => {
event.stopPropagation();
console.log("2, input");
});
// focus => input
// focusin => div && input
// focusin && stopPropagation => input
input
에 글을 작성하기 위해focus
이벤트가 발생해도 상위 요소인div
에 대한 이벤트도 발생하여 콘솔에는div, input
모두 찍히게 된다.focusin
을focus
로 변경하면input
에 대한 이벤트만 발생한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div id="box">
<ul id="list">
<li id="red">red</li>
<li id="blue">blue</li>
<li id="green">green</li>
<li id="yellow">yellow</li>
</ul>
</div>;
const list = document.getElementById("list");
const colors = list.children;
function clickHandler(evnet) {
for (each of colors) {
each.classList.remove("on");
}
event.target.classList.add("on");
}
document.getElementByI("red").addEventListener("click", clickHandler);
document.getElementByI("blue").addEventListener("click", clickHandler);
document.getElementByI("green").addEventListener("click", clickHandler);
document.getElementByI("yellow").addEventListener("click", clickHandler);
- 박스를 클릭하면 클리한 박스에
on
클래스를 추가하여 색상을 변경하는 코드가 있다고 가정한다. - 각
li
에 해당하는 모든 요소들에 대한 이벤트 코드를 작성해야 하지만, 갯수가 많아질수록 모든 코드를 작성하기 어려워진다. - 이 때, 이벤트 버블링을 사용하여 부모 요소에 핸들러 함수를 작성하면 된다.
- 자식 요소인
li
를 클릭해도 이벤트 버블링에 의해 부모 요소인ul
에도 이벤트가 전이되기 때문에 부모 요소에 이벤트 함수를 작성하면 된다.
1
document.getElementById("list").addEventListener("click", clickHandler);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<div id="box">
<ul id="list">
<li id="red">red</li>
<li id="blue">blue</li>
<li id="green">green</li>
<li id="yellow">yellow</li>
</ul>
</div>;
const list = document.getElementById("list");
const colors = list.children;
function clickHandler(evnet) {
console.log("target", event.target);
console.log("currentTarget", event.currentTarget);
for (each of colors) {
each.classList.remove("on");
}
event.target.classList.add("on");
}
// li를 눌렀을 시,
// target <li id="green" class="on">...</li>
// currentTarget <ul id="list">...</ul>
// a를 눌렀을 시,
// target <a href="#" class="on">green</a>
// currentTarget <ul id="list"></ul>
li
를 클릭했을 때,a
를 클리했을 때가 다르며,a
를 클릭 시, 글자의 배경색만 변경되는 어색한 점이 있다.target
은 이벤트를 발생시키는 요소,currentTarget
은 이벤트가 등록된 요소를 가르킨다.- 원하는 대로 동작시키기 위해서는
a
를 눌렀을 때, 부모 요소를 가르키도록 하면 된다.
1
2
3
4
5
6
7
8
9
10
11
function clickHandler(event) {
const target = event.target;
if (target.tagName === "a") {
target = target.parentElement;
}
for (each of colos) {
each.classList.remove("on");
}
target.classList.add("on");
}
- 이렇게 작성된 코드는, 만약 내가 클릭한 요소가
a
태그라면,a
를 클릭해도li
를 가르키게 되고 원하는 대로 배경색이 변경된다. - 하지만
ul
을 클릭했을 때,ul
상자의 배경색 또한 변경되는 데 이를 방지하기 위한 조건문도 작성한다.
1
2
3
4
5
6
7
8
9
function clickHandler(event) {
const target = event.target;
if (target.tagName === "a") {
target = target.parentElement;
} else if (target === event.currentTarget) {
// ul 이면
return;
}
}