자바스크립트-이벤트와 이벤트리스너

jaegeunsong97·2023년 9월 16일
0

Node.js

목록 보기
3/7

이벤트

  • 이벤트 종류
    • 마우스 이벤트
이벤트설명
click클릭했을 때
mouseout특정 요소에 마우스 영역을 벗어났을 때
mouserover특정요소 위에 마우스 포인터가 올라가져 있을 때
mousedown특정요소를 마우스로 눌렀을 때
mouseup특정요소를 마우스로 떼었을 때
mousemove특정 요소 위에서 마우스가 움직일 때
  • 키 이벤트
이벤트설명
keydown특정 키를 눌렀을 때
keyup특정 키를 떼었을 때
keypress특정 키를 누른 상태
  • 기타 이벤트
이벤트설명
focus특정 요소에 포커스 줄떄
blur특정 요소에 포커스가 벗어날 때
submitsubmit 버튼 클릭 시
resetreset 버튼 클릭 시
load페이지 로딩 완료될 때
unload페이지가 다른 곳으로 이동 시

이벤트 리스너

  • 특정 이벤트 발생시, 이벤트를 처리하는 기능
    • on + 이벤트 이름
이벤트 리스너설명
onclick클릭했을 때
onmouseout특정 요소에 마우스 영역을 벗어났을 때
onmouserover특정요소 위에 마우스 포인터가 올라가져 있을 때
onmousedown특정요소를 마우스로 눌렀을 때
onmouseup특정요소를 마우스로 떼었을 때
onmousemove특정 요소 위에서 마우스가 움직일 때
onkeydown특정 키를 눌렀을 때
onkeyup특정 키를 떼었을 때
onkeypress특정 키를 누른 상태
onfocus특정 요소에 포커스 줄떄
onblur특정 요소에 포커스가 벗어날 때
onsubmitsubmit 버튼 클릭 시
onresetreset 버튼 클릭 시
onload페이지 로딩 완료될 때
onunload페이지가 다른 곳으로 이동 시
  • HTML 태그의 속성으로 이벤트 처리
    • 간단한 방법, HTML에서 처리하는 것
    • <input type="button">
    • button에 click 이벤트가 발동하면 메시지 출력
    • onclick 핸들러 코드 길어지면 안되니까, 함수를 만들어 호출
    • 그럼에도 이벤트 리스너 onclick()이 HTML에 존재(문제)
// 1
<html>
     <head></head>
     <body>
          <input type="button" value="버튼" onclick="alert('버튼클릭')">
     </body>
</html>


// 2
<html>
     <head></head>
     <body>
          <input type="button" value="버튼" onclick=msg()>

          <script>
               function msg() { // 함수
                    alert('버튼클릭');
               }
          </script>
     </body>
</html>
  • 자바스크립트 영역에서 이벤트 처리
    • DOM 요소 : 버튼에 특정 이벤트 발생 시, 이벤트 핸들러를 통해 처리하겠다는 것
      • id로 사용
      • DOM요소.이벤트리스너 = 이벤트 핸들러
    • 단점 : 여러개의 이벤트 처리 불가능
// 1
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">

          <script>
               btnclk.onclick = function(){
                    alert('버튼클릭');
               }
          </script>
     </body>
</html>


// 2
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼" onclick=first()>

          <script>
               function first(){
                    alert('첫 번쨰 메시지');
               }
				
               btnclk.onclick = function(){ // 나 출력안됨....ㅠㅠ
                    alert('두 번쨰 메시지');
               }
          </script>
     </body>
</html>
  • addEventListener로 이벤트 등록(강추!!!!)
    • 여러개의 이벤트 등록 가능
    • DOM요소.addEventListener(이벤트 명, 실행할 함수명, 옵션)
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">

          <script>
               function first(){
                    alert('첫 번쨰 메시지');
                    alert("DOM : " + this.value) // 버튼 출력
               }
               
               btnclk.addEventListener('click', first);
               btnclk.addEventListener('click', function(){
                    alert('두 번쨰 메시지');
                    alert("DOM : " + this.value) // 버튼 출력
               });
          </script>
     </body>
</html>
  • removeEventListener로 이벤트 삭제
    • DOM요소.removeEventListener(이벤트 명, 등록했던 함수명)
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">

          <script>
               function first(){
                    alert('첫 번쨰 메시지');
                    alert("DOM : " + this.value)
               }
               
               btnclk.addEventListener('click', first);
               btnclk.addEventListener('click', function(){
                    alert('두 번쨰 메시지');
                    alert("DOM : " + this.value)
               });

               btnclk.removeEventListener('click', first);
               
          </script>
     </body>
</html>

이벤트 객체

  • 사용자 버튼 클릭 or DOM과 같은 이벤트 발생 => 이벤트 관련 정보 생성(이벤트 객체)
    • 이벤트 핸들러에게 매개변수 형태로 제공
    • 이벤트 객체의 속성 및 메소드
속성 및 메소드설명
currentTarget현재 이벤트를 처리중인 요소, 이벤트 핸들러 내부의 this와 동일
detail이벤트와 관련된 자세한 정보
preventDefault()이벤트 기본 동작 취소
stopPropagation이벤트 캡쳐링, 이벤트 버블링을 모두 취소
target이벤트 실제 요소
type발생한 이벤트 타입
clientX, clientY위치
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">

          <script>
               function msg(event) { // event : 이벤트 객체
                    alert(event.type);
                    alert("x좌표 : " + event.clientX);
                    alert("y좌표 : " + event.clientY);
               }

               btnclk.addEventListener('click', msg);
          </script>
     </body>
</html>
  • 객체형 이벤트 핸들러
    • handleEvent()
// 객체를 통한 이벤트 핸들러
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">

          <script>
               let obj ={ // 나는 객체!
                    handleEvent(event) { // 여기
                         alert(event.type);
                         alert("x좌표 : " + event.clientX);
                         alert("y좌표 : " + event.clientY);
                    }
               }

               btnclk.addEventListener('click', obj);
          </script>
     </body>
</html>


// 클래스를 통한 이벤트 핸들러
<html>
     <head></head>
     <body>
          <input type="button" id="btnclk" value="버튼">
          <div id="result"></div>
          <script>
               class Mouse {
                    handleEvent(event) {
                         switch(event.type) {
                              case 'mousedown':
                                   result.innerHTML = '마우스 버튼 누름';
                                   break;
                              case 'mouseup':
                                   result.innerHTML = '마우스 버튼 놓음';
                                   break;
                         }
                    }
               }

               let mouse = new Mouse();
               btnclk.addEventListener('mousedown', mouse);
               btnclk.addEventListener('mouseup', mouse);
          </script>
     </body>
</html>

콜백 함수

  • 고객이 커피를 요청했을 때, 주문 접수 받고 커피가 완성되면 점원이 고객을 호출하는 방식
  • 콜백의 중요 요소 : 함수를 변수에 넣기
function order(callback) {
	callback(); // 함수 포인터
}
  • 콜백 함수 생성
const coffee = function() {
     console.log('주문하신 아메리카노 나왔습니다.');
}

setTimeout(coffee, 5000); // 콜백 함수 예시
  • 이벤트 리스너와 콜백함수
    • 이벤트 리스너 == 콜백함수 : 이벤트 리스너와 연결되어 처리하는 함수인 이벤트 핸들러가 결국 콜백함수
    • DOM요소.addEventListener(이벤트명, 실행할 함수명(나다!!!!!!), 옵션)
    • DOM요소.addEventListener(이벤트명, 콜백 함수, 옵션)
<html>
     <head></head>
     <body>
          
          <button id="order1">주문1</button>
          <button id="order2">주문2</button>

          <script>
               const orderHandler1 = function() {
                    alert('주문하신 아메리카노 나왔습니다.');
               }

               const orderHandler2 = function() {
                    alert('주문하신 카페라뗴 나왔습니다.');
               }

               order1.onclick = orderHandler1;
               order2.addEventListener('click', orderHandler2); // 콜백함수이자 실행할 함수명
          </script>
     </body>
</html>
profile
현재 블로그 : https://jasonsong97.tistory.com/

0개의 댓글