본문 바로가기

프론트엔드/javascript

javascript (7) - Html, CSS, JavaScript, toggle

* js는 html에 영향을 주고 css는 html를 지켜보고있다!


html

<body>
    <div class="hello">
        <h1> Click me! </h1>
    </div>

    <script src="app.js"> </script>
</body>
js

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


function handleTitleClick() {
    const clickedClass = "clicked"
    if (h1.className === clickedClass) {
        h1.className = "";
    } else {
        h1.className = clickedClass;
    }
}

h1.addEventListener("click", handleTitleClick);
css

body {
    background-color: beige;


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

.clicked {
    color : tomato;
}

"string"을 변수에 저장하는건 아주 중요해! 에러가 발생하는 확률 낮춰준다

Bug -> html h1 에 class가 적용된 상태로 실행되면 기존 class는 새로운 class로 대체된다.

 

 

 

*기존 class name은 유지하고 clicked 만 변경하기

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


function handleTitleClick() {
    const clickedClass = "clicked"
    if (h1.classList.contains(clickedClass)) {
        h1.classList.remove(clickedClass); //true
    } else {
        h1.classList.add(clickedClass);
    }
}


h1.addEventListener("click", handleTitleClick);
-> const h1 = document.querySelector(".hello:first-child h1");


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


h1.addEventListener("click", handleTitleClick);

className = 이전 class 교체하지만 classList는 class 목록으로 작업할 수 있게 허용.

classList에는 적용 가능한 function 있다.

classList.contains("clicked") class에 "clicked"이 포함되어있는지 판단

classList.remove("clicked") class에서 "clicked" 제거

classList.add("clicked") class에서 "clicked" 추가

 

h1.classList.toggle("clicked");

h1의 class에 "clicked"가 존재하면 제거 없다면 추가해준다.

 

반응형

'프론트엔드 > javascript' 카테고리의 다른 글

javascript (9) - event.preventDefault  (0) 2023.04.04
javascript (8) - Login 만들기 #1  (0) 2023.04.03
javascript (6) - click event, window event  (0) 2023.04.03
javascript (5) - querySelector  (0) 2023.04.03
javascript (4)  (0) 2023.03.31