Vanilla js 이벤트 정리하기

IT쿠키·2022년 5월 12일
0

오랜만에 블로그를 쓴다!

좀 사족을 붙이자면 필자가 업무를 하다가 프론트를 하는 게 더 나을거 같아서 3개월만에 퇴사를 했다. 는 필요하지 않은 부분이니 넘어갑시다. 다음에 근황 다루면서 얘기를 할 예정

이벤트 정리하기

요번에 노마드 코더에서 하는 바닐라 js 챌린저가 있어서 도전 중에 정리한 내용이다.

  1. html 과 css 는 사용하지 않고 순수 바닐라 자바스크립트로만 활용할 것
  2. 각 이벤트를 총괄하는 이벤트로만 사용할 것
  3. 컬러는 배열에서 추출해서 사용할 것

이 세 가지가 중요한 목적인데

const body = document.querySelector("body");
let text = document.createElement("h2");
const colors = ["red", "blue", "purple", "black"];
text.innerText = "Title";
body.appendChild(text);
let title = text;
function colorPick() {
  let colorPicker = colors[Math.floor(Math.random() * colors.length)];
  title.style.color = colorPicker;
}

const superEventListener = {
  hoverEvent: function () {
    title.innerText = "the mouse over is here";
    colorPick();
  },
  leaveEvent: function () {
    title.innerText = "correct";
    colorPick();
  },
  resizeEvent: function () {
    title.innerText = "bye bye";
    colorPick();
  },
  clickEvent: function () {
    title.innerText = "click here";
    colorPick();
  }
};

title.addEventListener("mouseenter", superEventListener.hoverEvent);
title.addEventListener("mouseleave", superEventListener.leaveEvent);
window.addEventListener("resize", superEventListener.resizeEvent);
window.addEventListener("contextmenu", superEventListener.clickEvent);

일단 전체 코드는 이런 내용으로 작성을 진행했다.
1. 총괄하는 이벤트 부분은 상수로 작성해서 관리하기 용이하게 해주는 용도
2. mouseenter 와 mouseover의 차이는 over는 자식 요소 까지 포함이 되지만 enter 는 자기 자신에만 포함이 된다. 자매품 mouseleave 와 mouseout이 있다.
3. innterText 와 innerHtml 의 차이는 하나는 text 요소만 긁어오는 것이고 하나는 html 요소와 xml 까지 긁어온다.
4. resize event 같은 경우 document의 view 의 크기가 변경 될 때 발생이 된다.
여기서는 디바이스 창의 resize가 될시라 window에 달아줬다.

profile
IT 삶을 사는 쿠키

0개의 댓글