[miniP] JS 실습(조건문으로 글자색 바꾸기)

mokyoungg·2020년 4월 4일
0
const title = document.querySelector("#title");

const BASE_COLOR = "rgb(52, 73, 94)";
const OTHER_COLOR = "#7f8c8d";

function handleClick() {
  const currentColor = title.style.color;
  if (currentColor === BASE_COLOR) {
    title.style.color = OTHER_COLOR;
  } else {
    title.style.color = BASE_COLOR;
  }
}

function init() {
  title.style.color = BASE_COLOR;
  title.addEventListener("click", handleClick);
}

init();

노마드 코더 초보자를 위한 바닐라 자바스크립트
https://www.youtube.com/watch?v=UwnBvuFyiBU&list=PL7jH19IHhOLM8YwJMTa3UkXZN-LldYnyK&index=20

를 보며 따라하는데 2시간 걸렸다.

코드를 아무리 똑같이 작성하여도 작동하지 않았다.
혹시나 싶어 const BASE_COLOR와 const OTHER_COLOR 값까지 따라서 써보니 해결되었다.

영상 댓글을 보니 나와 비슷한 경우가 있는 것 같았다.
여기에 대한 노마드코더의 답은..

  • BASE_COLOR is on #HEX format and title.style.color expects RGB
  • Maybe because JS turns de #COLORCODE into rgba()

나도 BASE_COLOR 의 값을 HEX 값으로 주었는데 작동하지 않다가 이후 rgb값을 주니 작동하였다.

도대체 이게 무슨 일인가. 무슨 일이 일어나고 있는 것인가. 뭐지 왜지 왤까?? 구글을 찾아봐도 color convert 얘기뿐이다. 뭐지. 무슨 소리지. 저 답변에 답이 있는것같은데 모르겠다. 뭐지.뭐지.
???????????????????????????????????????????????????????????????????????????????


addEventListener

EventTarget의 addEventListener() 메서드는 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정합니다.
일반적인 대상은 element, document, window지만, XTLHttpRequest와 같이 이벤트를 지원하는 모든 객체를 대상으로 지정할 수 있습니다.

addEventListener()는 EventTarget의 주어진 이벤트 유형에, EventListener를 구현한 함수 또는 객체를 이벤트 처리기 목록에 추가해 작동합니다.

구문

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only
profile
생경하다.

0개의 댓글