티스토리 뷰

html 태그의 클래스를 remove, add를 하는 방법도 있지만 toggle 함수를 써서 더 간단하고 짧게 코드를 작성할 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>NomadCode JS Chrome App</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
h1 {
color: blue;
transition: color 0.5s ease-in-out;
}
.clicked {
color: tomato;
}
</style>
</head>
<body>
<div>
<h1 class="hello">Grab Me!</h1>
<h1 class="hello">Grab Me!</h1>
</div>
<script>
const h1 = document.querySelector('div .hello:first-child');
//태그.classList.remove || add 대신 toggle
function handleTitleClick() {
h1.classList.toggle('clicked'); //아래의 코드를 한 줄로 줄임
// const clickedClass = 'clicked';
// if (h1.classList.contains(clickedClass)) {
// h1.classList.remove(clickedClass);
// } else {
// h1.classList.add(clickedClass);
// }
}
h1.addEventListener('click', handleTitleClick);
</script>
<script src="script.js"></script>
</body>
</html>
아래는 실행 코드
Grab Me!
Grab Me!
'WEB > JavaScript' 카테고리의 다른 글
| [크롬 앱 만들기]#4.6 Loading Username | localStorage (0) | 2022.01.17 |
|---|---|
| [크롬 앱 만들기] #4.1 Form Submission | form -> submit (0) | 2022.01.16 |
| [크롬 앱 만들기] #3.6 css in js | getter setter (0) | 2022.01.16 |
| [제로초JS] chap8 반응속도테스트 (0) | 2022.01.14 |
| [제로초JS] chap7 가위바위보 (0) | 2022.01.13 |
댓글