CodeGym /행동 /Frontend SELF KO /이벤트 처리

이벤트 처리

Frontend SELF KO
레벨 41 , 레슨 4
사용 가능

5.1 이벤트 처리의 기초

JavaScript의 이벤트는 사용자와 상호작용하고 사용자의 행동에 반응하도록 해줘. 예를 들어 마우스 클릭, 키보드 입력, 폼의 변경 사항 등이 있어. 이벤트 핸들러를 추가하고 제거하는 방법을 아는 것은 인터랙티브 웹 애플리케이션 개발의 중요한 부분이야.

이벤트란 무엇인가?

이벤트는 브라우저에서 "무언가 발생했다"라고 알려주는 신호야. 예를 들어 사용자가 버튼을 클릭하거나 페이지가 로드되었을 때를 말이야. 이런 신호에 반응하여 특정한 동작을 수행할 수 있어.

이벤트의 종류

이벤트의 종류는 다양해. 가장 많이 사용되는 것들은 다음과 같아:

  • 마우스: click, dblclick, mouseover, mouseout, mousedown, mouseup, mousemove
  • 키보드: keydown, keyup, keypress
  • : submit, change, focus, blur
  • 문서/창: load, resize, scroll, unload

이벤트 핸들러

이벤트 핸들러(또는 이벤트 리스너)는 특정 이벤트에 반응하여 실행되는 함수야. 이벤트를 "듣고", 발생했을 때 실행돼.

5.2 이벤트 핸들러 추가하기

addEventListener로 이벤트 핸들러 추가하기

addEventListener 메소드는 요소에 이벤트 핸들러를 추가할 수 있게 해줘. 이건 onclick, onchange 같은 HTML 속성을 사용하는 전통적인 방법에 비해 더 유연하고 강력해.

문법:

    
      element.addEventListener(event, handler, options);
    
  

여기서:

  • element: 이벤트 핸들러를 추가할 요소
  • event: 반응할 이벤트의 타입 (예: 'click', 'input', 'keydown')
  • handler: 이벤트 발생 시 호출될 함수
  • options: 추가적인 옵션 (선택적 인자)

예제: click 이벤트 핸들러 추가

이 예제에서는 버튼에 이벤트 핸들러가 추가돼. 사용자가 버튼을 클릭하면 알림 메시지가 뜨게 돼.

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

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

          button.addEventListener('click', function() {
            alert('Button clicked!');
          });
        </script>
        </body>
      </html>
    
  

예제: 여러 이벤트 핸들러 추가

addEventListener를 사용하여 하나의 이벤트에 여러 핸들러를 추가할 수 있어.

이 예제에서는 두 개의 이벤트 핸들러가 버튼에 추가돼. 클릭 시 두 핸들러가 순차적으로 실행되어 콘솔에 각각의 메시지를 출력해.

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

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

            button.addEventListener('click', function() {
              console.log('First handler');
            });

            button.addEventListener('click', function() {
              console.log('Second handler');
            });
          </script>
        </body>
      </html>
    
  

5.3 options 매개변수 사용하기

options 매개변수는 이벤트 핸들러의 동작을 조정할 수 있어. 가장 많이 사용하는 옵션은:

  • once: true일 경우, 핸들러는 한 번만 실행되고 자동으로 제거돼
  • capture: true일 경우, 이벤트는 버블링 단계 대신 캡처 단계에서 처리돼
  • passive: true일 경우, 핸들러가 preventDefault()를 호출하지 않을 것을 나타내

예제: 한 번만 실행되는 핸들러

이 예제에서는 이벤트 핸들러가 딱 한 번만 실행되고 자동으로 제거돼.

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

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

            button.addEventListener('click', function() {
              alert('This will be shown only once');
            }, { once: true });
          </script>
        </body>
      </html>
    
  

5.4 이벤트 핸들러 제거하기

removeEventListener로 이벤트 핸들러 제거하기

removeEventListener 메소드는 addEventListener로 추가된 이벤트 핸들러를 제거할 수 있게 해줘. 핸들러를 추가할 때 사용한 것과 동일한 인자를 전달해야 해.

문법:

    
      element.removeEventListener(event, handler, options)
    
  

여기서:

  • element: 이벤트 핸들러가 제거될 요소
  • event: 핸들러를 제거할 이벤트의 타입
  • handler: 이벤트 핸들러로 지정된 함수
  • options: 추가적인 옵션 (핸들러 추가 시 사용한 것과 동일해야 해)

예제: click 이벤트 핸들러 제거

이 예제에서는 click 이벤트 핸들러가 버튼에 추가돼. 다른 버튼 클릭 시 click 이벤트 핸들러가 제거돼.

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

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

            function clickHandler() {
              alert('Button clicked!');
            }

            button.addEventListener('click', clickHandler);

            removeButton.addEventListener('click', function() {
              button.removeEventListener('click', clickHandler);
              alert('Click handler removed');
            });
          </script>
        </body>
      </html>
    
  
1
설문조사/퀴즈
DOM 요소, 레벨 41, 레슨 4
사용 불가능
DOM 요소
DOM 요소
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION