컴퓨터 공부/🕸️ Web

Javascript 에서의 toogle 함수

letzgorats 2021. 5. 28. 16:37

먼저 html 파일이 이런 html 파일이 있다고 해보자.

<html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <h1 id="title" class="btn">This is title!!</h1>
    <script src="clock.js"></script>
</body>
</html>

css 는 아래와 같다.

<css>

body {
  background-color: peru;
}

.btn {
  cursor: pointer;    // btn 클래스
}

h1 {
  color: #344952;
  transition: color 0.5s ease-in-out;
}

.clicked {
  color: red;    // clicked 클래스
}

 

javascript 는 아래와 같다.

<javascript>

const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handleClick(){
    const hasClass = title.classList.contains(CLICKED_CLASS);
    if(hasClass){
        title.classList.remove(CLICKED_CLASS);
    }
    else{
        title.classList.add(CLICKED_CLASS);
    }
}

function init(){
    title.addEventListener("click", handleClick);
    CLICKED_CLASS
}
init();

그러면, 제목을 클릭하였을 때,

title 이라는 id 값을 가지는 요소인 h1의 클래스에는 btn 이외에도 cliked 라는 클래스가 추가가 된다. 자연스럽게, color 값도 바뀌게 될 것이다. (classList 라는 것도 내장되어 있는 것이다.)

이러한 기능을 해주는 toggle 함수는 Javascript 에 내장되어 있다. 

즉, 위의 JS 를 아래와 같이 간단하게 바꿀 수 있다.

const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handleClick(){
   title.classList.toggle(CLICKED_CLASS);
}

function init(){
    title.addEventListener("click", handleClick);
    CLICKED_CLASS
}
init();

toggle은 해당 클래스가 있는지 없는지 체크해서

없으면, 넣어주고(add)

있으면, 삭제한다.(remove)

 

원래 클릭을 안 한 상태(혹은 클릭을 다시 했을 때)
클릭을 했을 때 clicked 라는 class 추가 

 

반응형