<body>
<div class="hello">
<h1>Grab me!</h1>
<script src="app.js"></script>
</div>
</body>
body {
background-color: beige;
}
h1 {
color: cornflowerblue;
transition: color 0.3s ease-in-out;
}
.active {
color: tomato;
}
const title = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
const activedClass = "active";
if (title.className === activedClass) {
title.className = "";
} else {
title.className = activedClass;
}
}
title.addEventListener("click", handleTitleClick);
const activedClass 라는 변수로, 코드를 수정할때 CSS에서 한 번만 복붙하게 함.
<body>
<div class="hello">
<h1 class="font">Grab me!</h1>
<script src="app.js"></script>
</div>
</body>
.active {
color: tomato;
}
.font {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
function handleTitleClick() {
const activedClass = "active";
if (title.classList.contains(activedClass)) {
title.classList.remove(activedClass);
} else {
title.classList.add(activedClass);
}
}
title.addEventListener("click", handleTitleClick);
title.classList.toggle("active");