자바스크립트/모던 자바스크립트 Deep Dive

이벤트

막이86 2023. 11. 20. 09:22
728x90

모던 자바스크립트 Deep Dive을 요약한 내용입니다.

40.1 이벤트 드리븐 프로그래밍

  • 브라우저는 처리해야 할 특정 사건이 발생하면 이를 감지하여 이벤트를 발생시킨다
  • 이벤트가 발생했을 때 호출될 함수를 이벤트 핸들러라고 한다.
  • 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 이벤트 핸들러 등록이라 한다.
  • 이벤트 중심으로 제어하는 프로그래밍 방식을 이벤트 드리븐 프로그래밍이라 한다.
<!DOCTYPE html>
<html>
  <body>
    <button>Click me!</button>
    <script>
      const $button = document.querySelector('button')
      $button.onclick = () => {
        alert('button click')
      }
    </script>
  </body>
</html>

40.2 이벤트 타입

  • 이벤트 타입은 이벤트의 종류를 나타내느 문자열이다.
  • 이벤트 타입은 약 200여 가지가 있다.

40.2.1 마우스 이벤트

이벤트 타입 이벤트 발생 시점

click 마우스 버튼을 클릭했을 때
dblclick 마우스 버튼을 더블 클릭했을 때
mousedown 마우스 버튼을 눌렀을 때
mouseup 누르고 있던 마우스 버튼을 놓았을 때
mousemove 마우스 커서를 움직였을 때
mouseenter 마우스 커서를 HTML 요소 안으로 이동했을 때(버블링되지 않는다.)
mouseover 마우스 커서를 HTML 요소 안으로 이동했을 때(버블링된다.)
mouseleave 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링되지 않는다.)
mouseout 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링된다.)

40.2.2 키보드 이벤트

이벤트 타입 이벤트 발생 시점

keydown 모든 키를 눌렀을 때 발생한다.
keypress 문자 키를 눌렀을 때 연속적으로 발생한다.
keyup 누르고 있던 키를 놓았을 때 한 번만 발생한다.

40.2.3 포커스 이벤트

이벤트 타입 이벤트 발생 시점

focus HTML 요소가 포커스를 받았을 때(버블링되지 않는다.)
blur HTML 요소가 포커스를 잃었을 때(버블링되지 않는다.)
focusin HTML 요소가 포커스를 받았을 때(버블링된다.)
focusout HTML 요소가 포커스를 잃었을 때(버블링된다.)

40.2.4 폼 이벤트

이벤트 타입 이벤트 발생 시점

submit form 요소 내의 submit 버튼을 클릭했을 때
reset form 요소 내의 reset 버튼을 클릭했을 때(최슨에는 사용 안함)

40.2.5 값 변경 이벤트

이벤트 타입 이벤트 발생 시점

input input(text, checkbox, radio), select, textarea 요소의 값이 입력되었을 때
change input(text, checkbox, radio), select, textarea 요소의 값이 변경되었을 때
readystatechange HTML 문서의 로드와 파싱 상태를 나타내는 readyState 프로퍼티 값(’loading’, ‘interactive’, ‘complete’)이 변경될 때

40.2.6 DOM 뮤테이션 이벤트

이벤트 타입 이벤트 발생 시점

DOMContentLoaded HTML 문서의 로드와 파싱이 완료되어 DOM 생성이 완료되었을 때

40.2.7 뷰 이벤트

이벤트 타입 이벤트 발생 시점

resize 브라우저 윈도우의 크기를 리사이즈할 때 연속적으로 발생한다.(오직 window 객체에서만 발생한다.)
scroll 웹페이지(document) 또는 HTML 요소를 스크롤할 때 연속적으로 발생한다.

40.2.8 리소스 이벤트

이벤트 타입 이벤트 발생 시점

load DOMContentLoaded 이벤트가 발생한 후, 모든 리소스의 로딩이 완료되었을 때(주로 widow 객체에서 발생)
unload 리소스가 언로드될 때(주로 새로운 웹페이지를 요청한 경우)
abort 리소스 로딩이 중단되었을 때
error 리소스 로딩이 실패했을 때

40.3 이벤트 핸들러 등록

  • 이벤트 핸들러는 이벤트가 발생했을 때 브라우저에 호출을 위임한 함수
  • 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 이벤트 핸들러 등록이라 한다.

40.3.1 이벤트 핸들러 어트리뷰트 방식

  • HTML 요소의 어트리뷰트 중에는 이벤트에 대응하는 이벤트 핸들러 어트리뷰트가 있다.
  • onclick과 같이 on 접두사와 이벤트의 종류를 나타내는 이벤트 타입으로 이루어져 있다.
  • 이벤트 핸들러 어트리뷰트 값으로 함수 호출문 등의 문을 할당하면 이벤트 핸들러가 등록된다.
<!DOCTYPE html>
<html>
  <body>
    <button onclick="sayHi('Lee')">Click me!</button>
    <script>
      function sayHi(name) {
        console.log(`Hi ${name}.`)
      }
    </script>
  </body>
</html>

40.3.2 이벤트 핸들러 프로퍼티 방식

  • window 객체와 Document, HTMLElement 타입의 DOM 노드 객체는 이벤트에 대응하는 이벤트 핸들러 프로퍼티를 가지고 있다.
  • 이벤트 핸들러 프로퍼티에 함수를 바인딩하면 이벤트 핸들러가 등록된다.
<!DOCTYPE html>
<html>
  <body>
    <button>Click me!</button>
    <script>
      const $button = document.querySelector('button')
      $button.onclick = () => {
        console.log('button click')
      }
    </script>
  </body>
</html>
  • 이벤트 핸들러를 등록하기 위해서는 이벤트를 발생시킬 객체인 이벤트 타깃과 이벤트 종류를 나타내느 문자열인 이벤트 타입 그리고 이벤트 핸들러를 지정할 필요가 있다.
  • 이벤트 핸들러 프로퍼티에 하나의 이벤트 핸들러만 바인딩할 수 있다는 단점이 있다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.onclick = () => { console.log('button click 1') } $button.onclick = () => { console.log('button click 2') } </script> </body> </html> // button click 2

40.3.3 addEventListener 메서드 방식

  • DOM. Level 2에서 도입된 EventTarget.prototype.addEventListener 메서드를 사용하여 이벤트 핸들러를 등록할 수 있다.
  • “이벤트 핸들러 어트리뷰트 방식”, “이벤트 핸들러 프로퍼티 방식”은 DOM Level 0부터 제공되던 방식이다.
  • addEventListener 메서드 사용
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.addEventListener('click', function () { console.log('button click') }) </script> </body> </html>
  • addEventListener 메서드 방식은 이벤트 핸들러 프로퍼티에 바인딩된 이벤트 핸들러에 아무런 영향을 주지 않는다.
    • 2개 이벤트 핸들러가 모두 호출된다.
    <!DOCTYPE html>
    <html>
      <body>
        <button>Click me!</button>
        <script>
          const $button = document.querySelector('button')
          $button.onclick = () => {
            console.log('[이벤트 핸들러 프로퍼티 방식] button click')
          }
          $button.addEventListener('click', function () {
            console.log('[addEventListener 메서드 방식] button click')
          })
        </script>
      </body>
    </html>
    // [이벤트 핸들러 프로퍼티 방식] button click
    // [addEventListener 메서드 방식] button click
    
  • addEventListener 메서드는 하나 이상의 이벤트 핸들러를 등록할 수 있다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.addEventListener('click', function () { console.log('[1] button click') }) $button.addEventListener('click', function () { console.log('[2] button click') }) </script> </body> </html> // [1] button click // [2] button click
  • 참조가 동일한 이벤트 핸들러를 중복 등록하면 하나의 이벤트 핸들러만 등록된다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') const handleClick = () => console.log('button click') $button.addEventListener('click', handleClick) $button.addEventListener('click', handleClick) </script> </body> </html> // button click

40.4 이벤트 핸들러 제거

  • EventTarget.prototype.remveEventListener 메서드를 사용하여 이벤트 핸들러를 제거할 수 있다.
  • addEventListener 메서드에 전달한 인수와 removeEventListener 메서드에 전달한 인수가 일치하지 않으면 이벤트 핸들러가 제거되지 않는다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') const handleClick = () => console.log('button click') $button.addEventListener('click', handleClick) $button.removeEventListener('click', handleClick, true) // 실패 $button.removeEventListener('click', handleClick) // 성공 </script> </body> </html>
  • 무명함수를 이벤트 핸들로 등록한 경우 제거할 수 없다.
  • $button.addEventListener('click', () => console.log('button click'))
  • 기명 이벤트 핸들러 내부에서 removeEventListener 메서드를 호출하여 이벤트 핸들러를 제거하는 것은 가능하다.
  • $button.addEventListener('click', function foo() { console.log('button click') $button.removeEventListener('click', foo) })
  • 이벤트 핸들러 프로퍼티 방식으로 등록한 이벤트 핸들러는 removeEventListener 메서드로 제거할 수 없다.
    • 이벤트 핸들러 프로퍼티에 null을 할 당한다.
    <!DOCTYPE html>
    <html>
      <body>
        <button>Click me!</button>
        <script>
          const $button = document.querySelector('button')
          const handleClick = () => console.log('button click')
    
          $button.onclick = handleClick
          // 제거 안됨
          $button.removeEventListener('click', handleClick)
    
          $button.onclick = null
        </script>
      </body>
    </html>
    

40.5 이벤트 객체

  • 이벤트가 발생하면 이벤트에 관련한 다양한 정보를 담고 있는 이벤트 객체가 동적으로 생성된다.
  • 생성된 이벤트 객체는 이벤트 핸들러의 첫 번째 인수로 전달된다.
    • 클릭 이벤트에 의해 생성된 이벤트 객체는 이벤트 핸들러의 첫 번째 인수로 전달되어 매개변수 e에 암묵적으로 할당된다.
    • e라는 이름으로 매개변수를 선언했으나 다른 이름을 사용하여도 상관없다.
    <!DOCTYPE html>
    <html>
      <body>
        <p>클릭하세요. 클릭한 곳의 좌표가 표시됩니다.</p>
        <em class="message"></em>
        <script>
          const $msg = document.querySelector('.message')
    
          function showCoords(e) {
            $msg.textContent = `clientX: ${e.clientX}, clientY: ${e.clientY}`
          }
          document.onclick = showCoords
        </script>
      </body>
    </html>
    
  • 이벤트 핸들러 어트리뷰트 방식으로 이벤트 핸들러를 등록했다면 event를 통해 이벤트 객체를 전달받을 수 있다.
  • // 동작 안함..... <!DOCTYPE html> <html> <body onclick="showCoords(event)"> <p>클릭하세요. 클릭한 곳의 좌표가 표시됩니다.</p> <em class="message"></em> <script> const $msg = document.querySelector('.message') function showCoords(e) { $msg.textContent = `clientX: ${e.clientX}, clientY: ${e.clientY}` } </script> </body> </html>
  • onclick=”showCoords(event)” 어트리뷰트는 파싱되어 다음과 같은 함수를 암묵적으로 생성하여 onclick 이벤트 핸들러 프로퍼티에 할당한다.
  • function onclick(event) { showCoords(event) }

40.5.1 이벤트 객체의 상속 구조

  • 이벤트 객체는 다음과 같은 상속 구조를 갖는다.
  • 이벤트가 발생하면 암묵적으로 생성되는 이벤트 객체도 생성자 함수에 의해 생성된다.
  • <!DOCTYPE html> <html> <body> <script> let e = new Event('foo') console.log(e) // Event {isTrusted: false, type: 'foo', target: null, currentTarget: null, eventPhase: 0, …} console.log(e.type) // foo console.log(e instanceof Event) // true console.log(e instanceof Object) // true e = new FocusEvent('focus') console.log(e) // FocusEvent {isTrusted: false, relatedTarget: null, view: null, detail: 0, sourceCapabilities: null, …} e = new MouseEvent('click') console.log(e) // MouseEvent {isTrusted: false, screenX: 0, screenY: 0, clientX: 0, clientY: 0, …} e = new KeyboardEvent('keyup') console.log(e) // KeyboardEvent {isTrusted: false, key: '', code: '', location: 0, ctrlKey: false, …} e = new InputEvent('change') console.log(e) // InputEvent {isTrusted: false, data: null, isComposing: false, inputType: '', dataTransfer: null, …} </script> </body> </html>
  • 이벤트 객체의 프로퍼티는 발생한 이벤트의 타입에 따라 달라진다.
  • <!DOCTYPE html> <html> <body> <input type="text" /> <input type="checkbox" /> <button>Click me!</button> <script> const $input = document.querySelector('input[type=text]') const $checkbox = document.querySelector('input[type=checkbox]') const $button = document.querySelector('button') // Event {isTrusted: true, type: 'load', target: document, currentTarget: Window, eventPhase: 2, …} window.onload = console.log // Event {isTrusted: true, type: 'change', target: input, currentTarget: input, eventPhase: 2, …} $checkbox.onchange = console.log // InputEvent {isTrusted: true, data: 'ㅇ', isComposing: true, inputType: 'insertCompositionText', dataTransfer: null, …} $input.oninput = console.log // KeyboardEvent {isTrusted: true, key: 'ㅇ', code: 'KeyD', location: 0, ctrlKey: false, …} $input.onkeyup = console.log // PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …} $button.onclick = console.log </script> </body> </html>

40.5.2 이벤트 객체의 공통 프로퍼티

  • 이벤트 객체의 공통 프로퍼티공통 프로퍼티 설명 타입
    type 이벤트 타입 string
    target 이벤트를 발생시킨 DOM 요소 DOM 요소 노드
    currentTarget 이벤트 핸들러가 바인딩된 DOM 요소 DOM 요소 노드
    eventPhase 이벤트 전파 단계 (0: 이벤트 없음, 1: 캡처링 단계, 2: 타깃 단계, 3: 버블링 단계) number
    bubbles 이벤트를 버블링으로 전파하는지 여부, 다음 이벤트는 bubbles: false로 버블링하지 않는다. boolean
    cancelable preventDefault 메서드를 호출하여 이벤트의 기본 동작을 취소할 수 있는지 여부, 다음 이벤트는 cancel: false로 취소할 수 없다. boolean
    defaultPrevented preventDefault 메서드를 호출하여 이벤트를 취소했는지 여부 boolean
    isTrusted 사용자의 행위에 의해 발생한 이벤트인지 여부 boolean
    timeStamp 이벤트가 발생한 시각 number
  • 체크박스 요소의 체크 상태가 변경되면 현재 체크 상태를 출력해보도록 하자.
  • <!DOCTYPE html> <html> <body> <input type="checkbox" /> <em class="message">off</em> <script> const $checkbox = document.querySelector('input[type=checkbox]') const $msg = document.querySelector('.message') $checkbox.onchange = (e) => { console.log(Object.getPrototypeOf(e) === Event.prototype) $msg.textContent = e.target.checked ? 'on' : 'off' } </script> </body> </html>

40.5.3 마우스 정보 취득

  • click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave 이벤트가 발생하면 생성되는 MouseEvent 타입의 이벤트 객체는 다음과 같은 고유의 프로퍼티를 갖는다.
    • 마우스 포인터의 좌표 정보를 나타내는 프로퍼티: screenX/screenY, clientX/clientY, pageX/pageY, offsetX/offsetY
    • 버튼 정보를 나타내는 프로퍼티: altKey, ctrlKey, shiftKey, button
  • 마우스 포인터 좌표 예제
  • <!DOCTYPE html> <html> <head> <style> .box { width: 100px; height: 100px; background-color: #fff700; border: 5px solid orange; cursor: pointer; } </style> </head> <body> <div class="box"></div> <script> const $box = document.querySelector('.box') const initailMousePos = { x: 0, y: 0 } const offset = { x: 0, y: 0 } const move = (e) => { offset.x = e.clientX - initailMousePos.x offset.y = e.clientY - initailMousePos.y $box.style.transform = `translate3d(${offset.x}px, ${offset.y}px, 0)` } $box.addEventListener('mousedown', (e) => { initailMousePos.x = e.clientX - offset.x initailMousePos.y = e.clientY - offset.y document.addEventListener('mousemove', move) }) document.addEventListener('mouseup', () => { document.removeEventListener('mousemove', move) }) </script> </body> </html>

40.5.4 키보드 정보 취득

  • input 요소의 입력 필드에 엔터 키가 입력되면 현재까지 입력 필드에 입력된 값을 출력하는 예제
  • <!DOCTYPE html> <html> <body> <input type="text" /> <em class="message"></em> <script> const $input = document.querySelector('input[type=text]') const $msg = document.querySelector('.message') $input.onkeyup = (e) => { if (e.key !== 'Enter') { return } $msg.textContent = e.target.value e.target.value = '' } </script> </body> </html>

40.6 이벤트 전파

  • DOM 트리 상에 존재하는 DOM 요소 노드에서 발생한 이벤트는 DOM 트리를 통해 전파된다.
    • ul 요소의 두 번째 요소인 li 요소를 클릭하면 클릭 이벤트가 발생한다.
    • 이때 생성된 이벤트 객체는 이벤트를 발생시킨 DOM 요소인 이벤트 타깃을 중심으로 DOM 트리를 통해 전파된다.
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> </body> </html>
  • ul 요소의 하위 요소인 li 요소를 클릭하여 이벤트를 발생시켜 보자
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> <script> const $fruits = document.getElementById('fruits') $fruits.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) </script> </body> </html> // 이벤트 단계: 3 // 이벤트 타겟: [object HTMLLIElement] // 커런트 타겟: [object HTMLUListElement]
  • 이벤트는 이벤트를 발생시킨 이벤트 타깃은 물론 상위 DOM 요소에서도 캐치할 수 있다.
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> <script> const $fruits = document.getElementById('fruits') const $banana = document.getElementById('banana') $fruits.addEventListener( 'click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }, true ) $banana.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) $fruits.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) </script> </body> </html>
  • 캡처링 단계의 이벤트와 버블링 단계의 이벤트를 캐치하는 이벤트 핸들러가 혼용되는 경우
    • body, button 요소는 버블링 단계의 이벤트만 캐치하고
    • p요소는 캡처링 단계의 이벤트만 캐치한다.
    ….내용이 잘 ㅠㅠ
  • <!DOCTYPE html> <html> <head> <style> html, body { height: 100%; } </style> </head> <body> <p>버블링과 캡처링 이벤트 <button>버튼</button></p> <script> document.body.addEventListener('click', () => { console.log('Handler fo body.') }) document.querySelector('p').addEventListener('click', () => { console.log('Handler for paragraph.') }, true) document.querySelector('button').addEventListener('click', () => { console.log('Handler for button') }) </script> </body> </html>

40.7 이벤트 위임

  • 사용자가 내비게이션 아이템을 클릭하여 선택하면 현재 선택된 내비게이션 아이템에 active 클래스를 추가하고 그 외의 모든 내비게이션 아이템의 active 클래스는 제거하는 예제
  • <!DOCTYPE html> <html> <head> <style> #fruits { display: flex; list-style-type: none; padding: 0; } #fruits li { width: 100px; cursor: pointer; } #fruits .active { color: red; text-decoration: underline; } </style> </head> <body> <nav> <ul id="fruits"> <li id="apple" class="active">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> </nav> <div>선택된 내비게이션 아이템: <em class="msg">apple</em></div> <script> const $fruits = document.getElementById('fruits') const $msg = document.querySelector('.msg') function activate({ target }) { ;[...$fruits.children].forEach(($fruit) => { $fruit.classList.toggle('active', $fruit === target) $msg.textContent = target.id }) } document.getElementById('apple').onclick = activate document.getElementById('banana').onclick = activate document.getElementById('orange').onclick = activate </script> </body> </html>
  • 이벤트 위임은 여러 개의 하위 DOM 요소에 각각 이벤트 핸들러를 등록하는 대신 하나의 상위 DOM 요소에 이벤트 핸들러를 등록하는 방법이다.
    • 이벤트 위임을 통해 처리할 때 주의할 점은 개발자가 기대한 DOM 요소가 아닐수 있다는 것
    • Element.prototype.matches 메서드는 인수로 전달된 선택자에 의해 특적 노드를 탐색 가능한지 확인
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          #fruits {
            display: flex;
            list-style-type: none;
            padding: 0;
          }
    
          #fruits li {
            width: 100px;
            cursor: pointer;
          }
    
          #fruits .active {
            color: red;
            text-decoration: underline;
          }
        </style>
      </head>
      <body>
        <nav>
          <ul id="fruits">
            <li id="apple" class="active">Apple</li>
            <li id="banana">Banana</li>
            <li id="orange">Orange</li>
          </ul>
        </nav>
        <div>선택된 내비게이션 아이템: <em class="msg">apple</em></div>
        <script>
          const $fruits = document.getElementById('fruits')
          const $msg = document.querySelector('.msg')
    
          function activate({ target }) {
            if (!target.matches('#fruits > li')) {
              return
            }
    
            ;[...$fruits.children].forEach(($fruit) => {
              $fruit.classList.toggle('active', $fruit === target)
              $msg.textContent = target.id
            })
          }
    
          $fruits.onclick = activate
        </script>
      </body>
    </html>
    

40.8 DOM 요소의 기본 동작의 조작

40.8.1 DOM 요소의 기본 동작 중단

  • 이벤트 객체의 preventDefault 메서드는 DOM 요소의 기본 동작을 중단시킨다.
  • go

40.8.2 이벤트 전파 방지

  • 이벤트 객체의 stopPropagation 메서드는 이벤트 전파를 중지시킨다.
    • btn2 요소는 자신이 발생시킨 이벤트가 전파되는 것을 중단하여 자신에게 바인딩된 이벤트 핸들러만 실행되도록 한다.
    <!DOCTYPE html>
    <html>
      <body>
        <div class="container">
          <button class="btn1">Button 1</button>
          <button class="btn2">Button 2</button>
          <button class="btn3">Button 3</button>
        </div>
        <script>
          document.querySelector('.container').onclick = ({ target }) => {
            if (!target.matches('.container > button')) {
              return
            }
            target.style.color = 'red'
          }
    
          document.querySelector('.btn2').onclick = (e) => {
            e.stopPropagation()
            e.target.style.color = 'blue'
          }
        </script>
      </body>
    </html>
    

40.9 이벤트 핸들러 내부의 this

40.9.1 이벤트 핸들러 어트리뷰트 방식

  • 이벤트 핸들러를 호출할 떄 인수로 전달한 this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
  • <!DOCTYPE html> <html> <body> <button onclick="handleClick(this)">Click me</button> <script> function handleClick(button) { console.log(button) // 이벤트를 바인딩한 button 요소 console.log(this) // window } </script> </body> </html>

40.9.2 이벤트 핸들러 프로퍼티 방식과 addEventListener 메서드 방식

  • 이ddEventListener 메서드 방식 모두 이벤트 핸들러 내부의 this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
    • 이벤트 핸들러 내부의 this는 이벤트 객체의 currentTaget 프로퍼티와 같다
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn1">0</button>
        <button class="btn2">0</button>
    
        <script>
          const $button1 = document.querySelector('.btn1')
          const $button2 = document.querySelector('.btn2')
    
          $button1.onclick = function (e) {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
            ++this.textContent
          }
    
          $button2.onclick = function (e) {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
            ++this.textContent
          }
        </script>
      </body>
    </html>
    
  • 화살표 함수로 정의한 이벤트 핸들러 내부의 this는 상위 스코프의 this를 가리킨다.
    • 화살표 함수는 함수 자체의 this 바인딩을 갖지 않는다.
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn1">0</button>
        <button class="btn2">0</button>
    
        <script>
          const $button1 = document.querySelector('.btn1')
          const $button2 = document.querySelector('.btn2')
    
          $button1.onclick = (e) => {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
    				// this는 window를 가리키므로 window.textContent에 NaN을 할당한다. 
            ++this.textContent
          }
    
          $button2.onclick = (e) => {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
    				// this는 window를 가리키므로 window.textContent에 NaN을 할당한다. 
            ++this.textContent
          }
        </script>
      </body>
    </html>
    
  • 클래스에서 이벤트 핸들러를 바인딩하는 경우 this에 주의해야 한다.
    • increase 메서드 내부의 this는 클래스가 생성할 인스턴스를 가리키지 않는다.
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn">0</button>
        <script>
          class App {
            constructor() {
              this.$button = document.querySelector('.btn')
              this.count = 0
    
              this.$button.onclick = this.increase
            }
    
            increase() {
              this.$button.textContent = ++this.count // Uncaught TypeError: Cannot set properties of undefined (setting 'textContent')
            }
          }
          new App()
        </script>
      </body>
    </html>
    
  • increase 메서드를 이벤트 핸들러로 바인딩할 때 bind 메서드를 사용해 this를 전달하여 increase 메서드 내부의 this가 클래스가 생성할 인스턴스를 가리키도록 해야 한다.
  • <!DOCTYPE html> <html> <body> <button class="btn">0</button> <script> class App { constructor() { this.$button = document.querySelector('.btn') this.count = 0 this.$button.onclick = this.increase.bind(this) } increase() { this.$button.textContent = ++this.count } } new App() </script> </body> </html>
  • 클래스 필드에 할당한 화살표 함수를 이벤트 핸들러로 등록하여 이벤트 핸들러 내부의 this가 인스턴스를 가리키도록 할 수도 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">0</button> <script> class App { constructor() { this.$button = document.querySelector('.btn') this.count = 0 this.$button.onclick = this.increase } increase = () => this.$button.textContent = ++this.count } new App() </script> </body> </html>

40.10 이벤트 핸들러에 인수 전달

  • 이벤트 핸들러 어트리뷰트 방식은 함수 호출문을 사용할 수 없기 때문에 인수를 전달할 수 있지만 이벤트 핸들러 프로퍼티 방식과 addEventListener 메서드 방식의 경우 이벤트 핸들러를 브라우저가 호출하기 때문에 함수 호출문이 아닌 함수 자체를 등록 해야한다.
    • 이벤트 핸들러 내부에서 함수를 호출하면 인수를 전달할 수 있다.
    <!DOCTYPE html>
    <html>
      <body>
        <label>User name <input type="text" /></label>
        <em class="message"></em>
        <script>
          const MIN_USER_NAME_LENGTH = 5
          const $input = document.querySelector('input[type=text]')
          const $msg = document.querySelector('.message')
    
          const checkUserNameLength = (min) => {
            $msg.textContent = $input.value.length < min ? `이름은 ${min}자 이상 입력해 주세요` : ''
          }
    
          $input.onblur = () => {
            checkUserNameLength(MIN_USER_NAME_LENGTH)
          }
        </script>
      </body>
    </html>
    
  • 이벤트 핸들러를 반환하는 함수를 호출하면 인수를 전달할 수도 있다.
  • <!DOCTYPE html> <html> <body> <label>User name <input type="text" /></label> <em class="message"></em> <script> const MIN_USER_NAME_LENGTH = 5 const $input = document.querySelector('input[type=text]') const $msg = document.querySelector('.message') const checkUserNameLength = (min) => (e) => { $msg.textContent = $input.value.length < min ? `이름은 ${min}자 이상 입력해 주세요` : '' } $input.onblur = checkUserNameLength(MIN_USER_NAME_LENGTH) </script> </body> </html>

40.11 커스텀 이벤트

40.11.1 커스텀 이벤트 생성

  • 기존 이벤트 타입이 아닌 임의의 문자열을 사용하여 새로운 이벤트 타입을 지정할 수도 있다.
  • const keyboardEvent = new KeyboardEvent('keyup') console.log(keyboardEvent.type) const customEvent = new CustomEvent('foo') console.log(customEvent.type)
  • 커스텀 이벤트 객체는 버블링되지 않으며 preventDefault 메서드로 취소할 수도 없다.
    • 커스텀 이벤트 객체는 bubbles, cancelable 프로퍼티 값이 false로 기본 설정
    • bubbles, cancelable 프로퍼티를 갖는 객체를 전달
    const customEvent = new MouseEvent('click', {
    	bubbles: true,
    	cancelable: true
    })
    
    console.log(customEvent.bubbles)     // true
    console.log(customEvent.cancelable)  // true
    

40.11.2 커스텀 이벤트 디스패치

  • 생성된 커스텀 이벤트는 dispatchEvent 메서드로 디스패치(이벤트를 발생시키는 행위)할 수 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">Click me</button> <script> const $button = document.querySelector('.btn') $button.addEventListener('click', (e) => { console.log(e) alert(`${e} Clicked!`) }) const customEvent = new MouseEvent('click') $button.dispatchEvent(customEvent) </script> </body> </html>
  • 일반적인 이벤트 핸들러는 비동기 처리 방식으로 동작하지만 dispatchEvent 메서드는 이벤트 핸들러를 동기 처리 방식으로 호출한다.
  • 커스텀 이벤트 생성자 함수에는 두번째 인수로 이벤트와 함께 전달하고 싶은 정보를 담은 detail 프로퍼티를 포함하는 객체를 전달할 수 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">Click me</button> <script> const $button = document.querySelector('.btn') $button.addEventListener('click', (e) => { alert(`${e.detail.message} Clicked!`) }) const customEvent = new CustomEvent('click', { detail: { message: 'Hello' } }) $button.dispatchEvent(customEvent) </script> </body> </html>
  • 임의의 이벤트 타입을 지정하여 커스텀 이벤트 객체를 생성한 경우 반드시 addEventListener 메서드 방식으로 이벤트 핸들러를 등록해야 한다.
  • 이벤트 핸들러 어트리뷰트/프로퍼티 방식을 사용할 수 없는 이유는 ‘on + 이벤트 타입’으로 이루어진 이벤트 핸들러 어트리뷰트/프로퍼티가 요소 노드에 존재하지 않기 때문이다.

40.1 이벤트 드리븐 프로그래밍

  • 브라우저는 처리해야 할 특정 사건이 발생하면 이를 감지하여 이벤트를 발생시킨다
  • 이벤트가 발생했을 때 호출될 함수를 이벤트 핸들러라고 한다.
  • 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 이벤트 핸들러 등록이라 한다.
  • 이벤트 중심으로 제어하는 프로그래밍 방식을 이벤트 드리븐 프로그래밍이라 한다.
<!DOCTYPE html>
<html>
  <body>
    <button>Click me!</button>
    <script>
      const $button = document.querySelector('button')
      $button.onclick = () => {
        alert('button click')
      }
    </script>
  </body>
</html>

40.2 이벤트 타입

  • 이벤트 타입은 이벤트의 종류를 나타내느 문자열이다.
  • 이벤트 타입은 약 200여 가지가 있다.

40.2.1 마우스 이벤트

이벤트 타입 이벤트 발생 시점

click 마우스 버튼을 클릭했을 때
dblclick 마우스 버튼을 더블 클릭했을 때
mousedown 마우스 버튼을 눌렀을 때
mouseup 누르고 있던 마우스 버튼을 놓았을 때
mousemove 마우스 커서를 움직였을 때
mouseenter 마우스 커서를 HTML 요소 안으로 이동했을 때(버블링되지 않는다.)
mouseover 마우스 커서를 HTML 요소 안으로 이동했을 때(버블링된다.)
mouseleave 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링되지 않는다.)
mouseout 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링된다.)

40.2.2 키보드 이벤트

이벤트 타입 이벤트 발생 시점

keydown 모든 키를 눌렀을 때 발생한다.
keypress 문자 키를 눌렀을 때 연속적으로 발생한다.
keyup 누르고 있던 키를 놓았을 때 한 번만 발생한다.

40.2.3 포커스 이벤트

이벤트 타입 이벤트 발생 시점

focus HTML 요소가 포커스를 받았을 때(버블링되지 않는다.)
blur HTML 요소가 포커스를 잃었을 때(버블링되지 않는다.)
focusin HTML 요소가 포커스를 받았을 때(버블링된다.)
focusout HTML 요소가 포커스를 잃었을 때(버블링된다.)

40.2.4 폼 이벤트

이벤트 타입 이벤트 발생 시점

submit form 요소 내의 submit 버튼을 클릭했을 때
reset form 요소 내의 reset 버튼을 클릭했을 때(최슨에는 사용 안함)

40.2.5 값 변경 이벤트

이벤트 타입 이벤트 발생 시점

input input(text, checkbox, radio), select, textarea 요소의 값이 입력되었을 때
change input(text, checkbox, radio), select, textarea 요소의 값이 변경되었을 때
readystatechange HTML 문서의 로드와 파싱 상태를 나타내는 readyState 프로퍼티 값(’loading’, ‘interactive’, ‘complete’)이 변경될 때

40.2.6 DOM 뮤테이션 이벤트

이벤트 타입 이벤트 발생 시점

DOMContentLoaded HTML 문서의 로드와 파싱이 완료되어 DOM 생성이 완료되었을 때

40.2.7 뷰 이벤트

이벤트 타입 이벤트 발생 시점

resize 브라우저 윈도우의 크기를 리사이즈할 때 연속적으로 발생한다.(오직 window 객체에서만 발생한다.)
scroll 웹페이지(document) 또는 HTML 요소를 스크롤할 때 연속적으로 발생한다.

40.2.8 리소스 이벤트

이벤트 타입 이벤트 발생 시점

load DOMContentLoaded 이벤트가 발생한 후, 모든 리소스의 로딩이 완료되었을 때(주로 widow 객체에서 발생)
unload 리소스가 언로드될 때(주로 새로운 웹페이지를 요청한 경우)
abort 리소스 로딩이 중단되었을 때
error 리소스 로딩이 실패했을 때

40.3 이벤트 핸들러 등록

  • 이벤트 핸들러는 이벤트가 발생했을 때 브라우저에 호출을 위임한 함수
  • 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 이벤트 핸들러 등록이라 한다.

40.3.1 이벤트 핸들러 어트리뷰트 방식

  • HTML 요소의 어트리뷰트 중에는 이벤트에 대응하는 이벤트 핸들러 어트리뷰트가 있다.
  • onclick과 같이 on 접두사와 이벤트의 종류를 나타내는 이벤트 타입으로 이루어져 있다.
  • 이벤트 핸들러 어트리뷰트 값으로 함수 호출문 등의 문을 할당하면 이벤트 핸들러가 등록된다.
<!DOCTYPE html>
<html>
  <body>
    <button onclick="sayHi('Lee')">Click me!</button>
    <script>
      function sayHi(name) {
        console.log(`Hi ${name}.`)
      }
    </script>
  </body>
</html>

40.3.2 이벤트 핸들러 프로퍼티 방식

  • window 객체와 Document, HTMLElement 타입의 DOM 노드 객체는 이벤트에 대응하는 이벤트 핸들러 프로퍼티를 가지고 있다.
  • 이벤트 핸들러 프로퍼티에 함수를 바인딩하면 이벤트 핸들러가 등록된다.
<!DOCTYPE html>
<html>
  <body>
    <button>Click me!</button>
    <script>
      const $button = document.querySelector('button')
      $button.onclick = () => {
        console.log('button click')
      }
    </script>
  </body>
</html>
  • 이벤트 핸들러를 등록하기 위해서는 이벤트를 발생시킬 객체인 이벤트 타깃과 이벤트 종류를 나타내느 문자열인 이벤트 타입 그리고 이벤트 핸들러를 지정할 필요가 있다.
  • 이벤트 핸들러 프로퍼티에 하나의 이벤트 핸들러만 바인딩할 수 있다는 단점이 있다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.onclick = () => { console.log('button click 1') } $button.onclick = () => { console.log('button click 2') } </script> </body> </html> // button click 2

40.3.3 addEventListener 메서드 방식

  • DOM. Level 2에서 도입된 EventTarget.prototype.addEventListener 메서드를 사용하여 이벤트 핸들러를 등록할 수 있다.
  • “이벤트 핸들러 어트리뷰트 방식”, “이벤트 핸들러 프로퍼티 방식”은 DOM Level 0부터 제공되던 방식이다.
  • addEventListener 메서드 사용
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.addEventListener('click', function () { console.log('button click') }) </script> </body> </html>
  • addEventListener 메서드 방식은 이벤트 핸들러 프로퍼티에 바인딩된 이벤트 핸들러에 아무런 영향을 주지 않는다.
    • 2개 이벤트 핸들러가 모두 호출된다.
    <!DOCTYPE html>
    <html>
      <body>
        <button>Click me!</button>
        <script>
          const $button = document.querySelector('button')
          $button.onclick = () => {
            console.log('[이벤트 핸들러 프로퍼티 방식] button click')
          }
          $button.addEventListener('click', function () {
            console.log('[addEventListener 메서드 방식] button click')
          })
        </script>
      </body>
    </html>
    // [이벤트 핸들러 프로퍼티 방식] button click
    // [addEventListener 메서드 방식] button click
    
  • addEventListener 메서드는 하나 이상의 이벤트 핸들러를 등록할 수 있다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') $button.addEventListener('click', function () { console.log('[1] button click') }) $button.addEventListener('click', function () { console.log('[2] button click') }) </script> </body> </html> // [1] button click // [2] button click
  • 참조가 동일한 이벤트 핸들러를 중복 등록하면 하나의 이벤트 핸들러만 등록된다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') const handleClick = () => console.log('button click') $button.addEventListener('click', handleClick) $button.addEventListener('click', handleClick) </script> </body> </html> // button click

40.4 이벤트 핸들러 제거

  • EventTarget.prototype.remveEventListener 메서드를 사용하여 이벤트 핸들러를 제거할 수 있다.
  • addEventListener 메서드에 전달한 인수와 removeEventListener 메서드에 전달한 인수가 일치하지 않으면 이벤트 핸들러가 제거되지 않는다.
  • <!DOCTYPE html> <html> <body> <button>Click me!</button> <script> const $button = document.querySelector('button') const handleClick = () => console.log('button click') $button.addEventListener('click', handleClick) $button.removeEventListener('click', handleClick, true) // 실패 $button.removeEventListener('click', handleClick) // 성공 </script> </body> </html>
  • 무명함수를 이벤트 핸들로 등록한 경우 제거할 수 없다.
  • $button.addEventListener('click', () => console.log('button click'))
  • 기명 이벤트 핸들러 내부에서 removeEventListener 메서드를 호출하여 이벤트 핸들러를 제거하는 것은 가능하다.
  • $button.addEventListener('click', function foo() { console.log('button click') $button.removeEventListener('click', foo) })
  • 이벤트 핸들러 프로퍼티 방식으로 등록한 이벤트 핸들러는 removeEventListener 메서드로 제거할 수 없다.
    • 이벤트 핸들러 프로퍼티에 null을 할 당한다.
    <!DOCTYPE html>
    <html>
      <body>
        <button>Click me!</button>
        <script>
          const $button = document.querySelector('button')
          const handleClick = () => console.log('button click')
    
          $button.onclick = handleClick
          // 제거 안됨
          $button.removeEventListener('click', handleClick)
    
          $button.onclick = null
        </script>
      </body>
    </html>
    

40.5 이벤트 객체

  • 이벤트가 발생하면 이벤트에 관련한 다양한 정보를 담고 있는 이벤트 객체가 동적으로 생성된다.
  • 생성된 이벤트 객체는 이벤트 핸들러의 첫 번째 인수로 전달된다.
    • 클릭 이벤트에 의해 생성된 이벤트 객체는 이벤트 핸들러의 첫 번째 인수로 전달되어 매개변수 e에 암묵적으로 할당된다.
    • e라는 이름으로 매개변수를 선언했으나 다른 이름을 사용하여도 상관없다.
    <!DOCTYPE html>
    <html>
      <body>
        <p>클릭하세요. 클릭한 곳의 좌표가 표시됩니다.</p>
        <em class="message"></em>
        <script>
          const $msg = document.querySelector('.message')
    
          function showCoords(e) {
            $msg.textContent = `clientX: ${e.clientX}, clientY: ${e.clientY}`
          }
          document.onclick = showCoords
        </script>
      </body>
    </html>
    
  • 이벤트 핸들러 어트리뷰트 방식으로 이벤트 핸들러를 등록했다면 event를 통해 이벤트 객체를 전달받을 수 있다.
  • // 동작 안함..... <!DOCTYPE html> <html> <body onclick="showCoords(event)"> <p>클릭하세요. 클릭한 곳의 좌표가 표시됩니다.</p> <em class="message"></em> <script> const $msg = document.querySelector('.message') function showCoords(e) { $msg.textContent = `clientX: ${e.clientX}, clientY: ${e.clientY}` } </script> </body> </html>
  • onclick=”showCoords(event)” 어트리뷰트는 파싱되어 다음과 같은 함수를 암묵적으로 생성하여 onclick 이벤트 핸들러 프로퍼티에 할당한다.
  • function onclick(event) { showCoords(event) }

40.5.1 이벤트 객체의 상속 구조

  • 이벤트 객체는 다음과 같은 상속 구조를 갖는다.
  • 이벤트가 발생하면 암묵적으로 생성되는 이벤트 객체도 생성자 함수에 의해 생성된다.
  • <!DOCTYPE html> <html> <body> <script> let e = new Event('foo') console.log(e) // Event {isTrusted: false, type: 'foo', target: null, currentTarget: null, eventPhase: 0, …} console.log(e.type) // foo console.log(e instanceof Event) // true console.log(e instanceof Object) // true e = new FocusEvent('focus') console.log(e) // FocusEvent {isTrusted: false, relatedTarget: null, view: null, detail: 0, sourceCapabilities: null, …} e = new MouseEvent('click') console.log(e) // MouseEvent {isTrusted: false, screenX: 0, screenY: 0, clientX: 0, clientY: 0, …} e = new KeyboardEvent('keyup') console.log(e) // KeyboardEvent {isTrusted: false, key: '', code: '', location: 0, ctrlKey: false, …} e = new InputEvent('change') console.log(e) // InputEvent {isTrusted: false, data: null, isComposing: false, inputType: '', dataTransfer: null, …} </script> </body> </html>
  • 이벤트 객체의 프로퍼티는 발생한 이벤트의 타입에 따라 달라진다.
  • <!DOCTYPE html> <html> <body> <input type="text" /> <input type="checkbox" /> <button>Click me!</button> <script> const $input = document.querySelector('input[type=text]') const $checkbox = document.querySelector('input[type=checkbox]') const $button = document.querySelector('button') // Event {isTrusted: true, type: 'load', target: document, currentTarget: Window, eventPhase: 2, …} window.onload = console.log // Event {isTrusted: true, type: 'change', target: input, currentTarget: input, eventPhase: 2, …} $checkbox.onchange = console.log // InputEvent {isTrusted: true, data: 'ㅇ', isComposing: true, inputType: 'insertCompositionText', dataTransfer: null, …} $input.oninput = console.log // KeyboardEvent {isTrusted: true, key: 'ㅇ', code: 'KeyD', location: 0, ctrlKey: false, …} $input.onkeyup = console.log // PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …} $button.onclick = console.log </script> </body> </html>

40.5.2 이벤트 객체의 공통 프로퍼티

  • 이벤트 객체의 공통 프로퍼티공통 프로퍼티 설명 타입
    type 이벤트 타입 string
    target 이벤트를 발생시킨 DOM 요소 DOM 요소 노드
    currentTarget 이벤트 핸들러가 바인딩된 DOM 요소 DOM 요소 노드
    eventPhase 이벤트 전파 단계 (0: 이벤트 없음, 1: 캡처링 단계, 2: 타깃 단계, 3: 버블링 단계) number
    bubbles 이벤트를 버블링으로 전파하는지 여부, 다음 이벤트는 bubbles: false로 버블링하지 않는다. boolean
    cancelable preventDefault 메서드를 호출하여 이벤트의 기본 동작을 취소할 수 있는지 여부, 다음 이벤트는 cancel: false로 취소할 수 없다. boolean
    defaultPrevented preventDefault 메서드를 호출하여 이벤트를 취소했는지 여부 boolean
    isTrusted 사용자의 행위에 의해 발생한 이벤트인지 여부 boolean
    timeStamp 이벤트가 발생한 시각 number
  • 체크박스 요소의 체크 상태가 변경되면 현재 체크 상태를 출력해보도록 하자.
  • <!DOCTYPE html> <html> <body> <input type="checkbox" /> <em class="message">off</em> <script> const $checkbox = document.querySelector('input[type=checkbox]') const $msg = document.querySelector('.message') $checkbox.onchange = (e) => { console.log(Object.getPrototypeOf(e) === Event.prototype) $msg.textContent = e.target.checked ? 'on' : 'off' } </script> </body> </html>

40.5.3 마우스 정보 취득

  • click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave 이벤트가 발생하면 생성되는 MouseEvent 타입의 이벤트 객체는 다음과 같은 고유의 프로퍼티를 갖는다.
    • 마우스 포인터의 좌표 정보를 나타내는 프로퍼티: screenX/screenY, clientX/clientY, pageX/pageY, offsetX/offsetY
    • 버튼 정보를 나타내는 프로퍼티: altKey, ctrlKey, shiftKey, button
  • 마우스 포인터 좌표 예제
  • <!DOCTYPE html> <html> <head> <style> .box { width: 100px; height: 100px; background-color: #fff700; border: 5px solid orange; cursor: pointer; } </style> </head> <body> <div class="box"></div> <script> const $box = document.querySelector('.box') const initailMousePos = { x: 0, y: 0 } const offset = { x: 0, y: 0 } const move = (e) => { offset.x = e.clientX - initailMousePos.x offset.y = e.clientY - initailMousePos.y $box.style.transform = `translate3d(${offset.x}px, ${offset.y}px, 0)` } $box.addEventListener('mousedown', (e) => { initailMousePos.x = e.clientX - offset.x initailMousePos.y = e.clientY - offset.y document.addEventListener('mousemove', move) }) document.addEventListener('mouseup', () => { document.removeEventListener('mousemove', move) }) </script> </body> </html>

40.5.4 키보드 정보 취득

  • input 요소의 입력 필드에 엔터 키가 입력되면 현재까지 입력 필드에 입력된 값을 출력하는 예제
  • <!DOCTYPE html> <html> <body> <input type="text" /> <em class="message"></em> <script> const $input = document.querySelector('input[type=text]') const $msg = document.querySelector('.message') $input.onkeyup = (e) => { if (e.key !== 'Enter') { return } $msg.textContent = e.target.value e.target.value = '' } </script> </body> </html>

40.6 이벤트 전파

  • DOM 트리 상에 존재하는 DOM 요소 노드에서 발생한 이벤트는 DOM 트리를 통해 전파된다.
    • ul 요소의 두 번째 요소인 li 요소를 클릭하면 클릭 이벤트가 발생한다.
    • 이때 생성된 이벤트 객체는 이벤트를 발생시킨 DOM 요소인 이벤트 타깃을 중심으로 DOM 트리를 통해 전파된다.
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> </body> </html>
  • ul 요소의 하위 요소인 li 요소를 클릭하여 이벤트를 발생시켜 보자
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> <script> const $fruits = document.getElementById('fruits') $fruits.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) </script> </body> </html> // 이벤트 단계: 3 // 이벤트 타겟: [object HTMLLIElement] // 커런트 타겟: [object HTMLUListElement]
  • 이벤트는 이벤트를 발생시킨 이벤트 타깃은 물론 상위 DOM 요소에서도 캐치할 수 있다.
  • <!DOCTYPE html> <html> <body> <ul id="fruits"> <li id="apple">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> <script> const $fruits = document.getElementById('fruits') const $banana = document.getElementById('banana') $fruits.addEventListener( 'click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }, true ) $banana.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) $fruits.addEventListener('click', (e) => { console.log(`이벤트 단계: ${e.eventPhase}`) console.log(`이벤트 타겟: ${e.target}`) console.log(`커런트 타겟: ${e.currentTarget}`) }) </script> </body> </html>
  • 캡처링 단계의 이벤트와 버블링 단계의 이벤트를 캐치하는 이벤트 핸들러가 혼용되는 경우
    • body, button 요소는 버블링 단계의 이벤트만 캐치하고
    • p요소는 캡처링 단계의 이벤트만 캐치한다.
    ….내용이 잘 ㅠㅠ
  • <!DOCTYPE html> <html> <head> <style> html, body { height: 100%; } </style> </head> <body> <p>버블링과 캡처링 이벤트 <button>버튼</button></p> <script> document.body.addEventListener('click', () => { console.log('Handler fo body.') }) document.querySelector('p').addEventListener('click', () => { console.log('Handler for paragraph.') }, true) document.querySelector('button').addEventListener('click', () => { console.log('Handler for button') }) </script> </body> </html>

40.7 이벤트 위임

  • 사용자가 내비게이션 아이템을 클릭하여 선택하면 현재 선택된 내비게이션 아이템에 active 클래스를 추가하고 그 외의 모든 내비게이션 아이템의 active 클래스는 제거하는 예제
  • <!DOCTYPE html> <html> <head> <style> #fruits { display: flex; list-style-type: none; padding: 0; } #fruits li { width: 100px; cursor: pointer; } #fruits .active { color: red; text-decoration: underline; } </style> </head> <body> <nav> <ul id="fruits"> <li id="apple" class="active">Apple</li> <li id="banana">Banana</li> <li id="orange">Orange</li> </ul> </nav> <div>선택된 내비게이션 아이템: <em class="msg">apple</em></div> <script> const $fruits = document.getElementById('fruits') const $msg = document.querySelector('.msg') function activate({ target }) { ;[...$fruits.children].forEach(($fruit) => { $fruit.classList.toggle('active', $fruit === target) $msg.textContent = target.id }) } document.getElementById('apple').onclick = activate document.getElementById('banana').onclick = activate document.getElementById('orange').onclick = activate </script> </body> </html>
  • 이벤트 위임은 여러 개의 하위 DOM 요소에 각각 이벤트 핸들러를 등록하는 대신 하나의 상위 DOM 요소에 이벤트 핸들러를 등록하는 방법이다.
    • 이벤트 위임을 통해 처리할 때 주의할 점은 개발자가 기대한 DOM 요소가 아닐수 있다는 것
    • Element.prototype.matches 메서드는 인수로 전달된 선택자에 의해 특적 노드를 탐색 가능한지 확인
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          #fruits {
            display: flex;
            list-style-type: none;
            padding: 0;
          }
    
          #fruits li {
            width: 100px;
            cursor: pointer;
          }
    
          #fruits .active {
            color: red;
            text-decoration: underline;
          }
        </style>
      </head>
      <body>
        <nav>
          <ul id="fruits">
            <li id="apple" class="active">Apple</li>
            <li id="banana">Banana</li>
            <li id="orange">Orange</li>
          </ul>
        </nav>
        <div>선택된 내비게이션 아이템: <em class="msg">apple</em></div>
        <script>
          const $fruits = document.getElementById('fruits')
          const $msg = document.querySelector('.msg')
    
          function activate({ target }) {
            if (!target.matches('#fruits > li')) {
              return
            }
    
            ;[...$fruits.children].forEach(($fruit) => {
              $fruit.classList.toggle('active', $fruit === target)
              $msg.textContent = target.id
            })
          }
    
          $fruits.onclick = activate
        </script>
      </body>
    </html>
    

40.8 DOM 요소의 기본 동작의 조작

40.8.1 DOM 요소의 기본 동작 중단

  • 이벤트 객체의 preventDefault 메서드는 DOM 요소의 기본 동작을 중단시킨다.
  • go

40.8.2 이벤트 전파 방지

  • 이벤트 객체의 stopPropagation 메서드는 이벤트 전파를 중지시킨다.
    • btn2 요소는 자신이 발생시킨 이벤트가 전파되는 것을 중단하여 자신에게 바인딩된 이벤트 핸들러만 실행되도록 한다.
    <!DOCTYPE html>
    <html>
      <body>
        <div class="container">
          <button class="btn1">Button 1</button>
          <button class="btn2">Button 2</button>
          <button class="btn3">Button 3</button>
        </div>
        <script>
          document.querySelector('.container').onclick = ({ target }) => {
            if (!target.matches('.container > button')) {
              return
            }
            target.style.color = 'red'
          }
    
          document.querySelector('.btn2').onclick = (e) => {
            e.stopPropagation()
            e.target.style.color = 'blue'
          }
        </script>
      </body>
    </html>
    

40.9 이벤트 핸들러 내부의 this

40.9.1 이벤트 핸들러 어트리뷰트 방식

  • 이벤트 핸들러를 호출할 떄 인수로 전달한 this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
  • <!DOCTYPE html> <html> <body> <button onclick="handleClick(this)">Click me</button> <script> function handleClick(button) { console.log(button) // 이벤트를 바인딩한 button 요소 console.log(this) // window } </script> </body> </html>

40.9.2 이벤트 핸들러 프로퍼티 방식과 addEventListener 메서드 방식

  • 이ddEventListener 메서드 방식 모두 이벤트 핸들러 내부의 this는 이벤트를 바인딩한 DOM 요소를 가리킨다.
    • 이벤트 핸들러 내부의 this는 이벤트 객체의 currentTaget 프로퍼티와 같다
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn1">0</button>
        <button class="btn2">0</button>
    
        <script>
          const $button1 = document.querySelector('.btn1')
          const $button2 = document.querySelector('.btn2')
    
          $button1.onclick = function (e) {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
            ++this.textContent
          }
    
          $button2.onclick = function (e) {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
            ++this.textContent
          }
        </script>
      </body>
    </html>
    
  • 화살표 함수로 정의한 이벤트 핸들러 내부의 this는 상위 스코프의 this를 가리킨다.
    • 화살표 함수는 함수 자체의 this 바인딩을 갖지 않는다.
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn1">0</button>
        <button class="btn2">0</button>
    
        <script>
          const $button1 = document.querySelector('.btn1')
          const $button2 = document.querySelector('.btn2')
    
          $button1.onclick = (e) => {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
    				// this는 window를 가리키므로 window.textContent에 NaN을 할당한다. 
            ++this.textContent
          }
    
          $button2.onclick = (e) => {
            console.log(this)
            console.log(e.currentTarget)
            console.log(this === e.currentTarget)
    
    				// this는 window를 가리키므로 window.textContent에 NaN을 할당한다. 
            ++this.textContent
          }
        </script>
      </body>
    </html>
    
  • 클래스에서 이벤트 핸들러를 바인딩하는 경우 this에 주의해야 한다.
    • increase 메서드 내부의 this는 클래스가 생성할 인스턴스를 가리키지 않는다.
    <!DOCTYPE html>
    <html>
      <body>
        <button class="btn">0</button>
        <script>
          class App {
            constructor() {
              this.$button = document.querySelector('.btn')
              this.count = 0
    
              this.$button.onclick = this.increase
            }
    
            increase() {
              this.$button.textContent = ++this.count // Uncaught TypeError: Cannot set properties of undefined (setting 'textContent')
            }
          }
          new App()
        </script>
      </body>
    </html>
    
  • increase 메서드를 이벤트 핸들러로 바인딩할 때 bind 메서드를 사용해 this를 전달하여 increase 메서드 내부의 this가 클래스가 생성할 인스턴스를 가리키도록 해야 한다.
  • <!DOCTYPE html> <html> <body> <button class="btn">0</button> <script> class App { constructor() { this.$button = document.querySelector('.btn') this.count = 0 this.$button.onclick = this.increase.bind(this) } increase() { this.$button.textContent = ++this.count } } new App() </script> </body> </html>
  • 클래스 필드에 할당한 화살표 함수를 이벤트 핸들러로 등록하여 이벤트 핸들러 내부의 this가 인스턴스를 가리키도록 할 수도 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">0</button> <script> class App { constructor() { this.$button = document.querySelector('.btn') this.count = 0 this.$button.onclick = this.increase } increase = () => this.$button.textContent = ++this.count } new App() </script> </body> </html>

40.10 이벤트 핸들러에 인수 전달

  • 이벤트 핸들러 어트리뷰트 방식은 함수 호출문을 사용할 수 없기 때문에 인수를 전달할 수 있지만 이벤트 핸들러 프로퍼티 방식과 addEventListener 메서드 방식의 경우 이벤트 핸들러를 브라우저가 호출하기 때문에 함수 호출문이 아닌 함수 자체를 등록 해야한다.
    • 이벤트 핸들러 내부에서 함수를 호출하면 인수를 전달할 수 있다.
    <!DOCTYPE html>
    <html>
      <body>
        <label>User name <input type="text" /></label>
        <em class="message"></em>
        <script>
          const MIN_USER_NAME_LENGTH = 5
          const $input = document.querySelector('input[type=text]')
          const $msg = document.querySelector('.message')
    
          const checkUserNameLength = (min) => {
            $msg.textContent = $input.value.length < min ? `이름은 ${min}자 이상 입력해 주세요` : ''
          }
    
          $input.onblur = () => {
            checkUserNameLength(MIN_USER_NAME_LENGTH)
          }
        </script>
      </body>
    </html>
    
  • 이벤트 핸들러를 반환하는 함수를 호출하면 인수를 전달할 수도 있다.
  • <!DOCTYPE html> <html> <body> <label>User name <input type="text" /></label> <em class="message"></em> <script> const MIN_USER_NAME_LENGTH = 5 const $input = document.querySelector('input[type=text]') const $msg = document.querySelector('.message') const checkUserNameLength = (min) => (e) => { $msg.textContent = $input.value.length < min ? `이름은 ${min}자 이상 입력해 주세요` : '' } $input.onblur = checkUserNameLength(MIN_USER_NAME_LENGTH) </script> </body> </html>

40.11 커스텀 이벤트

40.11.1 커스텀 이벤트 생성

  • 기존 이벤트 타입이 아닌 임의의 문자열을 사용하여 새로운 이벤트 타입을 지정할 수도 있다.
  • const keyboardEvent = new KeyboardEvent('keyup') console.log(keyboardEvent.type) const customEvent = new CustomEvent('foo') console.log(customEvent.type)
  • 커스텀 이벤트 객체는 버블링되지 않으며 preventDefault 메서드로 취소할 수도 없다.
    • 커스텀 이벤트 객체는 bubbles, cancelable 프로퍼티 값이 false로 기본 설정
    • bubbles, cancelable 프로퍼티를 갖는 객체를 전달
    const customEvent = new MouseEvent('click', {
    	bubbles: true,
    	cancelable: true
    })
    
    console.log(customEvent.bubbles)     // true
    console.log(customEvent.cancelable)  // true
    

40.11.2 커스텀 이벤트 디스패치

  • 생성된 커스텀 이벤트는 dispatchEvent 메서드로 디스패치(이벤트를 발생시키는 행위)할 수 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">Click me</button> <script> const $button = document.querySelector('.btn') $button.addEventListener('click', (e) => { console.log(e) alert(`${e} Clicked!`) }) const customEvent = new MouseEvent('click') $button.dispatchEvent(customEvent) </script> </body> </html>
  • 일반적인 이벤트 핸들러는 비동기 처리 방식으로 동작하지만 dispatchEvent 메서드는 이벤트 핸들러를 동기 처리 방식으로 호출한다.
  • 커스텀 이벤트 생성자 함수에는 두번째 인수로 이벤트와 함께 전달하고 싶은 정보를 담은 detail 프로퍼티를 포함하는 객체를 전달할 수 있다.
  • <!DOCTYPE html> <html> <body> <button class="btn">Click me</button> <script> const $button = document.querySelector('.btn') $button.addEventListener('click', (e) => { alert(`${e.detail.message} Clicked!`) }) const customEvent = new CustomEvent('click', { detail: { message: 'Hello' } }) $button.dispatchEvent(customEvent) </script> </body> </html>
  • 임의의 이벤트 타입을 지정하여 커스텀 이벤트 객체를 생성한 경우 반드시 addEventListener 메서드 방식으로 이벤트 핸들러를 등록해야 한다.
  • 이벤트 핸들러 어트리뷰트/프로퍼티 방식을 사용할 수 없는 이유는 ‘on + 이벤트 타입’으로 이루어진 이벤트 핸들러 어트리뷰트/프로퍼티가 요소 노드에 존재하지 않기 때문이다.
728x90

'자바스크립트 > 모던 자바스크립트 Deep Dive' 카테고리의 다른 글

비동기 프로그래밍  (0) 2023.11.20
타이머  (2) 2023.11.20
브라우저의 렌더링 과정  (1) 2023.11.17
Set과 Map  (0) 2023.11.17
디스트럭처링 할당  (0) 2023.11.17