새소식

Frontend/JavaScript

[JavaScript] 노마드코더 강의 정리 - Events&CSS in JS

  • -

 

📒 Events

  • 자바스크립트가 주로 하는 일 : event listen
  • event : click, input, enter, disconnect from wifi…
  • console.dir(title): element 내부의 property 알 수 있음
  • on으로 시작하는 속성들이 이벤트

 

How to use Events

// 1. addEventListener 사용
// removeEventListner로 삭제 가능
title.addEventListener("click", handleTitleClick);

// 2. window 이벤트 사용
(title).onclick = handleTitleClick;

 

 

Window events

function handleWindowResize() {
  document.body.style.backgroundColor = "tomato";
}

window.addEventListener("resize", handleWindowResize);

// head, body, title 등은 document 객체로 호출 가능

 

 

addEventListner

function handleTitleClick() {
  h1.style.color = "blue"; // JS에서도 CSS 수정 가능하지만 CSS에서 수정하는 게 더 적합함 
}

function handleMouseEnter() {
  h1.innerText = "Mouse is here!";
}

function handleMouseLeave() {
  h1.innerText = "Mouse is gone!";
}

h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);

 

 

📒 CSS in JavaScript

 

JS에서 CSS 수정하기

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

console.dir(h1);

function handleClick() {
  const currentColor = h1.style.color; //getter, 현재 상태의 color값 대입
  let newColor; //setter, 클릭시 바뀔 color 값, 변경되기 때문에 let 사용

  if (currentColor === "blue") {
    newColor = "tomato";
  } else {
    newColor = "blue";
  }
  h1.style.color = newColor; //글자색 변경
}

h1.addEventListener("click", handleClick);

 

 

함수 마지막 줄에 'h1.style.color = newcolor'를 왜 넣는 건지 이해가 안 갔는데 댓글들을 보면서 이해했다.

 

사용자가 h1 태그를 클릭시 handleClick() 함수가 실행되고, h1.style.color는 currentColor에 대입해

if문에서 현재 색상 값을 비교한다. 마지막 줄에 newColor의 색상 값을 웹에서 확인할 수 있는

h1.style.color에 대입해 색상 변경. 대입하지 않으면 newColor라는 변수는 쓸모가 없어짐

 

currenColor, newColor로 변수를 나눈 이유는

두 변수가 가지는 의미가 다르기 때문에 따로 지정하는 것. 

 

후 어렵다...ㅎㅎ 이해 안 되는 코드는 한 줄 한 줄 해석해보기.

 

 

 

className

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

function handleClick() {
  const clickedClass = "clicked";
  if (h1.className === "clickedClass") { 
    // "clicked" : raw strings, 에러 발생을 줄이기 위해 변수에 할당
    // 그러면 변수 이름 틀려도 console이 알려줌

    h1.className = "";
  } else {
    h1.className = "clickedClass";
  }
}

h1.addEventListener("click", handleClick);

className은 원래있던 h1 class 이름을 교체함

 

classList

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

classList 사용시 원래있던 h1 class 이름 옆에 clicked가 생김

 

toggle

function handleClick() {
  h1.classList.toggle("clicked")
}

위 코드 다섯 줄을 토글을 이용해 한 줄로 바꿀 수 있음(Eureka!)

toggle은 classList에 clikced 존재 유무를 판단해 생성, 제거 함

전원 on/off, 스마트폰 잠금/해제 같은 기능에 사용 가능

 

 


 

 

참고 자료

 

바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders

Javascript For Beginners

nomadcoders.co

 

Web APIs | MDN

When writing code for the Web, there are a large number of Web APIs available. Below is a list of all the APIs and interfaces (object types) that you may be able to use while developing your Web app or site.

developer.mozilla.org

 

DOMTokenList - Web API | MDN

The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList (en-US), HTMLAnchorElement.relList (en-US), HTMLAreaElement.relList (en-US), HTMLIframeElement.sandbox, or HTMLOutpu

developer.mozilla.org

 

 

 

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.