event : click, input, enter, disconnect from wifi…
console.dir(title): element 내부의 property 알 수 있음
on으로 시작하는 속성들이 이벤트
How to use Events
// 1. addEventListener 사용
// removeEventListner로 삭제 가능
title.addEventListener("click", handleTitleClick);
// 2. window 이벤트 사용
(title).onclick = handleTitleClick;
Window events
function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}
window.addEventListener("resize", handleWindowResize);
// head, body, title 등은 document 객체로 호출 가능
addEventListner
function handleTitleClick() {
h1.style.color = "blue"; // JS에서도 CSS 수정 가능하지만 CSS에서 수정하는 게 더 적합함
}
function handleMouseEnter() {
h1.innerText = "Mouse is here!";
}
function handleMouseLeave() {
h1.innerText = "Mouse is gone!";
}
h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);
📒 CSS in JavaScript
JS에서 CSS 수정하기
const h1 = document.querySelector("div.hello:first-child h1");
console.dir(h1);
function handleClick() {
const currentColor = h1.style.color; //getter, 현재 상태의 color값 대입
let newColor; //setter, 클릭시 바뀔 color 값, 변경되기 때문에 let 사용
if (currentColor === "blue") {
newColor = "tomato";
} else {
newColor = "blue";
}
h1.style.color = newColor; //글자색 변경
}
h1.addEventListener("click", handleClick);
함수 마지막 줄에 'h1.style.color = newcolor'를 왜 넣는 건지 이해가 안 갔는데 댓글들을 보면서 이해했다.
사용자가 h1 태그를 클릭시 handleClick() 함수가 실행되고, h1.style.color는 currentColor에 대입해
if문에서 현재 색상 값을 비교한다. 마지막 줄에 newColor의 색상 값을 웹에서 확인할 수 있는
h1.style.color에 대입해 색상 변경. 대입하지 않으면 newColor라는 변수는 쓸모가 없어짐
currenColor, newColor로 변수를 나눈 이유는
두 변수가 가지는 의미가 다르기 때문에 따로 지정하는 것.
후 어렵다...ㅎㅎ 이해 안 되는 코드는 한 줄 한 줄 해석해보기.
className
const h1 = document.querySelector("div.hello:first-child h1");
function handleClick() {
const clickedClass = "clicked";
if (h1.className === "clickedClass") {
// "clicked" : raw strings, 에러 발생을 줄이기 위해 변수에 할당
// 그러면 변수 이름 틀려도 console이 알려줌
h1.className = "";
} else {
h1.className = "clickedClass";
}
}
h1.addEventListener("click", handleClick);
className은 원래있던 h1 class 이름을 교체함
classList
function handleClick() {
const clickedClass = "clicked";
if (h1.classList.contains(clickedClass)) {
h1.classList.remove(clickedClass);
} else {
h1.classList.add(clickedClass);
}
}
classList 사용시 원래있던 h1 class 이름 옆에 clicked가 생김
toggle
function handleClick() {
h1.classList.toggle("clicked")
}