# 22-07-07

어제 구현했던 드래그 앤 드랍이 모바일 환경에서는 동작하지 않았다. 기존 구현했던 드래그 앤 드랍은 mouse이벤트를 이용하여 구현한 드래그 앤 드랍이었고, 모바일 환경에서는 이 이벤트가 동작하지 않고 touch를 이용해야 했다.

# 바닐라 JavaScript로 Drag & Drop 구현하기 🖱️ - 1.5 모바일 환경에서 Drag & Drop 구현

# 모바일 드래그 앤 드랍을 위한 이벤트 추가

  • mousedown 👉 touchstart
  • mousemove 👉 touchmove
  • mouseup 👉 touchend, touchcancel

# offsetX의 구현

touch이벤트로는 offsetX, offsetY(selectedBox에서 touchstart가 인식된 영역 -mouse이벤트의 경우 mousedown이 인식된 영역-)를 구할 수 없었다. 아래 방법으로 직접 계산하여 주었다.

$wrap.addEventListener("touchstart", ({ target, targetTouches }) => {
  if (!target.classList.contains("box")) {
    return;
  }

  selectedBox = target;
  selectedBoxRect = selectedBox.getBoundingClientRect();

  offset = {
    x: targetTouches[0].pageX - selectedBoxRect.left,
    y: targetTouches[0].pageY - selectedBoxRect.top,
  };
});

# mouseleave 의 모바일 환경으로 구현

기존 mouseleave의 경우에는 $wrap 영역을 벗어나는 경우($wrap.addEventListener("mouseleave"...)로 구현 하였으나, Touch event types (opens new window)에는 touchleave이벤트가 없으므로 직접 $wrap의 좌표를 구해주는 방법으로 구현하였다.

const left = $wrap.offsetLeft;
const top = $wrap.offsetTop;
const height = $wrap.offsetHeight;
const width = $wrap.offsetWidth;

// mousemove 이벤트 핸들러 내에서 아래 조건문 적용
if (
  firstTouch.pageX > width ||
  firstTouch.pageY > height ||
  firstTouch.pageX < top ||
  firstTouch.pageY < left
) {
  // 아래는 mouseleave 이벤트 핸들러의 내용과 같음
  if (!selectedBox) {
    return;
  }

  selectedBox.style.opacity = 1;
  selectedBox = null;
  selectedBoxRect = null;
}

코드는 리팩토링🔨예정이다.

# 구현 화면

모바일📱 환경에서 확인해보자(개발자 도구를 이용해서도 확인 가능하다🤓)


# 알고리즘 문제풀이

# BOJ 18126 - 너구리 구구

너구리 구구 (opens new window)문제를 재귀를 이용해 풀이 (opens new window)하였는데, 틀렸던 이유가 양방향임을 간과했기 때문이었다😖. 문제의 주어진 조건을 집중해서 확인하고, 빠뜨리지 않도록 노력해야겠다.

  • 피드백 - 리팩토링🔨 해보기
    • const loadObject = {}; 전역변수 삭제
    • for문 대신, 고차함수 사용해보기