VanillaJS 0419

Sammy·2022년 4월 19일
0

App.js

const h1 = document.querySelector("div.hello:first-child h1");

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

h1.addEventListener("click",handleTitleClick);

위 코드는 아래 코드와 같은 이벤트를 발생한다.
Click 이벤트를 구현할 때 classList 에 active라는 className이 포함되어 있다면 active를 제거하고 포함되어있지 않다면 active를 추가한다.

const h1 = document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
  h1.classList.toggle("active");
}

h1.addEventListener("click",handleTitleClick);

classList.toggle 은 기존에 있던 className을 제거하지 않고 새로운 className을 add와 remove 할 수 있다.

style.css

body{
  background-color: beige;
}
h1{
  color: cornflowerblue;
  transition: color .5s ease-in-out;
}

.active{
  color: tomato;
}
profile
Web Developer

0개의 댓글