티스토리 뷰

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>

아래는 실행 코드

NomadCode JS Chrome App

Grab Me!

Grab Me!

댓글
다크모드
Document description javascript psychology
더보기 ,제목1 태그 호버