HTML, CSS, JS 활용법

Heewon👩🏻‍💻·2024년 4월 25일

HTML 코드

  <body>
    <div class="hello">
      <h1>Grab me!</h1>
      <script src="app.js"></script>
    </div>
  </body>

CSS 코드

body {
  background-color: beige;
}

h1 {
  color: cornflowerblue;
  transition: color 0.3s ease-in-out;
}

.active {
  color: tomato;
}

JS코드

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에서 한 번만 복붙하게 함.

🧐 "className" 을 사용하게되면 기존에 html에 설정된 class가 전부 대체되어버리는 문제점이 있다. 그렇다면 기존 class이름을 유지시키면서 새로운 class를 추가하려면 어케해야하나? "classList"를 사용하면 된다.

HTML

<body>
    <div class="hello">
      <h1 class="font">Grab me!</h1>
      <script src="app.js"></script>
    </div>
</body>

CSS

.active {
  color: tomato;
}
.font {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

JS

function handleTitleClick() {
  const activedClass = "active";
  if (title.classList.contains(activedClass)) {
    title.classList.remove(activedClass);
  } else {
    title.classList.add(activedClass);
  }
}

title.addEventListener("click", handleTitleClick);

💡 classList에는 toggle이란 함수가있는데, 자동으로 지정된 클래스명이 있는지 없는지 확인하고, 있으면 제거 없으면 추가하는 기능을 포함한다. 그래서 if로 시작한 코드 5줄을 한줄로 줄일 수 있다.

title.classList.toggle("active");
profile
Interested in coding, meat lover, in love with dogs , enjoying everything happens in my life.

0개의 댓글