JavaScript/기초

CSS in JavaScript

고기고기물고기 2022. 3. 20. 05:58

목표 - CSS 해당 클래스에 디자인 설정을 해두고 클래스를 변경 혹은 추가해서 디자인 설정하기

app.js

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

function handleClickEvent () {
    const activeClass = "active";
    if (title.className === activeClass)
    {
        title.className = "";
    } 
    else 
    {
        title.className = activeClass;
    }
}

h1.addEventListener("click", handleTitleClick);

css

h1{
color: cornflowerblue
}

body{
background-color : beige;
}

.active {
color: tomato;
}

index.html

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

문제점 : CSS는 잘 적용이 되자만 클래스명이 바뀜 원래 클래스 값을 잃어버림

 

해결방법

 

App.js

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

function handleClickEvent () {
    const activeClass = "active";
    if (h1.classList.contains(activeClass)
    {
        h1.classList.remove(clickedClass);
    } 
    else 
    {
        h1.classList.add(activeClass);
    }
}

h1.addEventListener("click", handleTitleClick);

원래의 클래스를 갖고, 클릭시 클래스 추가 및 제거됨

 

간단하게 한줄로만 표현 가능

 

function handleClickEvent () 
{
	h1.classList.toggle("active");
}
h1.addEventListener("click", handleTitleClick);