Front-end/Vanila JS

[JS] CSS in JS

탱 'ㅅ' 2024. 4. 25. 16:12

style에 적합한 도구는 CSS
animation에 적합한 도구는 JS

 

step 1. Find the element.

step 2. Listen for an event.

step 3. React to that event. (show, hide, change color of sth, ...)

 

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

function handleTitleClick() {

    // change color
    const currentColor = h1.style.color // getter
    let newColor
    if (currentColor === 'blue') {
    	newColor = 'tomato'
    	// h1.style.color = 'toamto' // 비추천
	} else {
    	newColor = 'blue'
    }
    h1.style.color = newColor // setter
    
    
    // change class
    const clickedClass = 'clicked'
    h1.classList.toggle(clickedClass)
    /*
    if (h1.classList.contains(clickedClass)) {
    	h1.classList.remove(clickedClass)
    } else {
    	h1.classList.add(clickedClass)
        // h1.classList.add('clicked') // 비추천 
    }
    */
}

h1.addEventListener('click', handleTitleClick)

 

h1.style.color : getter + setter

 

속성명과 값에 각각 변수를 선언하여 정의하는 이유

의미적으로 무엇을 하려는 코드인지 가독성이 올라간다.

불필요하게 반복되는 코드를 호출하지 않아도 된다.

🔖 .js 파일보다는 .css 에서 하는 것을 추천.

 

 

클래스명에 raw string 값이 아닌 변수로 정의하는 이유

단순히 사용자가 정의한 클래스명이기 때문에 

.css와 .js에서 모두 철자가 완전 동일해야하는데 

타이핑 실수로 인한 오류 확률을 줄여준다.

🔖 raw value가 반복되면 상수로 선언하여 재사용할 것.

 

* raw string 이란?

\ 그 다음에 오는 문자있는 그대로 받아들이는 string

All kinds of escape characters will be ineffective and backslashes will be present in the output string.

 

String.raw() - JavaScript | MDN

String.raw()메서드는 템플릿 리터럴의 태그 함수입니다. 이는 Pyhon의 r 접두사 또는 C#의 문자열 리터럴의 @ 접두사와 유사합니다.(그러나 동일 하지는 않습니다. 이 문제에 관해서는 여기 이슈를 참

developer.mozilla.org

 

 

element.classList.toggle(:className)

클래스 여부를 확인하여 있으면 제거하고 없으면 추가한다.

불필요한 조건문을 사용하지 않아도 된다.

 

DOMTokenList: toggle() method - Web APIs | MDN

The toggle() method of the DOMTokenList interface removes an existing token from the list and returns false. If the token doesn't exist it's added and the function returns true.

developer.mozilla.org

 

'Front-end > Vanila JS' 카테고리의 다른 글

[JS] Math 객체  (0) 2024.05.23
[JS] variables - var, let, const (scope, hoisting)  (0) 2024.04.29
[JS] Console 객체  (0) 2024.04.24
[JS] Events  (0) 2023.12.27
[JS] HTML in JS (document 객체) 📌  (0) 2023.12.21