JS에서도 CSS를 적용하거나 변경할 수 있지만
스타일 관련된건 CSS에서, 인터랙션과 관련된건 JS에서 하는게 좋다
(라고 니꼴라스쌤이 ..!)
const h1=document.querySelector("div.hello:first-child h1");
h1.addEventListener("click",handleTitleClick);
click me!라고 적힌 h1 element를 클릭하면 색깔이 blue에서 tomato로 변하게 해보자
-> currentColor, newColor이라는 변수를 사용해서 오류 줄이기
function handleTitleClick(){
const currentColor=h1.style.color;
let newColor;
if(currentColor==="blue"){
newColor="tomato";
}
else{
newColor="blue";
}
h1.style.color=newColor;
}
-> h1의 기본색깔 속성은 colorflowerblue로 해두고 자바스크립트에서 .active 클래스의 속성을 통해 바꿔보자
classList.contains , classList.add , classList.remove 알아보기
<!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 App</title>
</head>
<body>
<div class="hello">
<h1 class="sexy-font">click me!</h1>
<h1>Grab me!2</h1>
<h1>Grab me!3</h1>
</div>
<script src="app.js"></script>
</body>
</html>
h1 {
color: cornflowerblue;
transition: color 0.5s ease-in-out;
}
.active {
color: tomato;
}
.sexy-font {
font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}
function handleTitleClick(){
const clickedClass="active";
if(h1.classList.contains(clickedClass){
h1.classList.add(clickedClass);
}
else{
h1.classList.remove(clickedClass);
}
}
toggle: (이 예시에서) h1의 classList에 clickedClass 가 이미 있는지 확인해서 없다면 추가, 있다면 제거
--> 마치 스위치 같은 편리한 기능!
function handleTitleClick(){
const clickedClass="active";
h1.classList.toggle(clickedClass);
}