CodeGym /행동 /Frontend SELF KO /이벤트 객체의 속성과 메서드

이벤트 객체의 속성과 메서드

Frontend SELF KO
레벨 42 , 레슨 0
사용 가능

6.1 이벤트 객체

JavaScript는 다양한 사용자 동작 및 브라우저에서 발생하는 다른 이벤트를 추적할 수 있는 강력한 이벤트 시스템을 제공해. 이벤트를 다룰 때 중요한 측면은 이벤트에 대한 정보를 포함하고 처리 메서드를 제공하는 이벤트 객체이야.

이벤트가 발생하면 브라우저는 해당 이벤트에 대한 정보를 담고 있는 이벤트 객체를 생성해. 이 객체는 이벤트 핸들러에 인수로 전달돼.

이벤트 객체의 속성:

  1. type: 이벤트의 유형 (예: click, keydown).
  2. target: 이벤트가 발생한 요소.
  3. currentTarget: 이벤트 핸들러가 연결된 요소.
  4. eventPhase: 이벤트의 단계 (캡처, 타겟, 버블링).
  5. bubbles: 이벤트가 버블링될 수 있는지를 나타내는 논리 값.
  6. cancelable: 이벤트를 취소할 수 있는지를 나타내는 논리 값.
  7. defaultPrevented: 기본 동작이 방지되었는지를 나타내는 논리 값.
  8. timeStamp: 이벤트가 생성된 시간.
  9. isTrusted: 이벤트가 사용자에 의해 생성되었는지 스크립트에 의해 생성되었는지를 나타내는 논리 값.

이벤트 객체의 메서드:

  1. preventDefault(): 이벤트와 관련된 기본 동작을 취소해.
  2. stopPropagation(): 이벤트의 추가 전파를 중지해.
  3. stopImmediatePropagation(): 이벤트의 추가 전파를 중지하고 현재 요소에 대한 다른 이벤트 핸들러의 실행을 방지해.

이벤트 객체 사용 예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Event Object Example</title>
        </head>
        <body>
          <button id="myButton">Click me</button>

          <script>
            const button = document.getElementById('myButton');

            button.addEventListener('click', function(event) {
              console.log('Event type:', event.type); // 출력: click
              console.log('Event target:', event.target); // 출력: <button id="myButton">Click me</button>
              console.log('Current target:', event.currentTarget); // 출력: <button id="myButton">Click me</button>
              console.log('Event phase:', event.eventPhase); // 출력: 2 (타겟 단계)
              console.log('Bubbles:', event.bubbles); // 출력: true
              console.log('Cancelable:', event.cancelable); // 출력: true
              console.log('Time stamp:', event.timeStamp); // 출력: 밀리초 단위 시간
              console.log('Is trusted:', event.isTrusted); // 출력: true
            });
          </script>
        </body>
      </html>
    
  

6.2. 마우스 이벤트 (Mouse Events)

마우스 이벤트는 사용자가 마우스를 사용하여 요소와 상호 작용할 때 생성돼:

  • click: 클릭 이벤트
  • dblclick: 더블 클릭 이벤트
  • mousedown: 마우스 버튼을 누를 때 발생하는 이벤트
  • mouseup: 마우스 버튼을 뗄 때 발생하는 이벤트
  • mousemove: 마우스 이동 이벤트
  • mouseover: 마우스를 올렸을 때 발생하는 이벤트
  • mouseout: 마우스가 나갈 때 발생하는 이벤트

예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Mouse Events Example</title>
        </head>
        <body>
          <button id="myButton">Click Me</button>
          <script>
            const button = document.getElementById('myButton');

            button.addEventListener('click', function(event) {
              console.log('Button clicked');
              console.log('Event type:', event.type);
              console.log('Target element:', event.target);
            });
          </script>
        </body>
      </html>
    
  

6.3 로드 이벤트 (Load Events)

로드 이벤트는 리소스가 로드를 완료할 때 발생해:

  • load: 리소스/페이지가 완전히 로드되었을 때 발생하는 이벤트
  • DOMContentLoaded: 초기 HTML 문서가 로드되고 스타일 시트, 이미지 및 하위 프레임의 완전한 로드를 기다리지 않고 구문 분석될 때 발생하는 이벤트

예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Load Events Example</title>
        </head>
        <body>
          <script>
            window.addEventListener('load', function(event) {
              console.log('Window fully loaded');
            });

            document.addEventListener('DOMContentLoaded', function(event) {
              console.log('DOM fully loaded and parsed');
            });
          </script>
        </body>
      </html>
    
  

6.4 포커스 이벤트 (Focus Events)

포커스 이벤트는 요소가 포커스를 받거나 잃을 때 생성돼.

  • focus: 요소가 포커스를 받을 때 발생하는 이벤트
  • blur: 요소가 포커스를 잃을 때 발생하는 이벤트

예제:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Focus Events Example</title>
        </head>
        <body>
          <input type="text" id="textInput" placeholder="Type something...">
          <script>
            const input = document.getElementById('textInput');

            input.addEventListener('focus', function(event) {
              console.log('Input field focused');
            });

            input.addEventListener('blur', function(event) {
              console.log('Input field lost focus');
            });
          </script>
        </body>
      </html>
    
  

6.5 키보드 이벤트 (Keyboard Events)

키보드 이벤트는 사용자가 키보드에서 키를 눌렀을 때 생성돼:

  • keydown: 키가 눌렸을 때 발생하는 이벤트
  • keyup: 키가 릴리스되었을 때 발생하는 이벤트
  • keypress: 키가 눌리고 릴리스될 때 발생하는 이벤트 (구식, 사용 권장하지 않음)

예제:

HTML
    
      <html>
        <head>
          <title>Keyboard Events Example</title>
        </head>
        <body>
          <input type="text" id="textInput" placeholder="Type something...">
          <script>
            const input = document.getElementById('textInput');

            input.addEventListener('keydown', function(event) {
              console.log('Key down:', event.key);
            });

            input.addEventListener('keyup', function(event) {
              console.log('Key up:', event.key);
            });
          </script>
        </body>
      </html>
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION