본문 바로가기

JavaScript

[JS] DOM & EVENT #5 이벤트 핸들러(Event Handler)

1. Event Handler 할당하기

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <button onclick = "alert('클릭했습니다')"> 클릭 </button>
  </body>

 

 

DOM Events

 

HTML DOM Event Object

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

: Event의 속성들이 있다. 어떤 것들이 있는지 살펴보면 좋다.

 

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <button onclick="alert('클릭했습니다')">클릭</button>
    <button onclick="sayHello()">클릭2</button>
    <button id="btn">클릭3</button>
    <button id="btn2">클릭4</button>

    <script>
      function sayHello() {
        alert("Hello"); //괄호가 없어야한다. 괄호가 있으면 함수의 반환값이 할당되기 때문.
      }

      const el = document.getElementById("btn");
      el.onclick = sayHello

      const el2 = document.getElementById("btn2");
      el2.addEventListener("click", sayHello); //addEventListener: 특정 이벤트가 발생하면 핸들러(전달된 함수)를 실행한다.

    </script>
  </body>
</html>

위와 같은 코드가 있다고 가정해보자.

클릭, 클릭2, 클릭3, 클릭4를 보면 각자 다른 방식의 button event 코드가 있다는 것을 알 수 있다.

 

 

   addEventListener

  • :특정 이벤트가 발생하면 핸들러(전달된 함수)를 실행한다.
  • Handler는 이벤트 객체를 인수로 받는다

 

 el2.addEventListener("click", sayHello);

sayHello 자리엔 직접 전달하는 것도 가능하다.

el2.addEventListener("click", () => {
alert("hi");
});

 

결과

 

 

+  removeEventListener

: 이미 할당된 이벤트를 지울 때 사용한다.

 

 


 

   focus와 blur

  • focus: 입력창에 마우스를 눌렀을 때 발생
  • blur: focus 잃을 때

✏️입력

input.addEventListener("focus", () => {
  input.style.backgroundColor = "rgba(255,-0,0,0.2)";
  });
  
  input.addEventListener("blur", () => {
    input.style.backgroundColor = null; // null: 초기화시킨다
    });

📍결과

  • 입력창 클릭시 설정한 rgb값의 색이 보여지고, 포쿠스를 떼면 초기화시킨다.

 


 

   mousemove

  • 마우스를 움직였을때마다 이벤트 발생

✏️입력

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <div
      id="box"
      style="width: 100px; height: 100px; border: 2px solod red"
    ></div>  
    <script>
     const box = document.getElementById("box");
     box.addEventListener("mousemove", event => {
     console.log(event);
     });
    </script>
  </body>
</html>

📍결과

: 이 네모박스 안에서 마우스를 움직일 때마다 console에서 마우스의 위치값이 계속 뜨는 것을 확인할 수 있다.

 

: 잘 안보이겠지만..

clientX: 54

clientY: 111 이라고 적혀있다.

이것을 통해 현재 마우스 포인터의 위치를 알 수 있다.

 

 

✨심화) 커서를 따라다니는 동그라미 만드는 방법

✏️입력

  • 천천히 따라하면서 이해하면 될 것 같다.
<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <!DOCTYPE html>
    <html>
      <head>
        <title>Welcome</title>
      </head>
      <body>
        <div
          id="box"
          style="
            position: relative; 
            width: 100px;
            height: 100px;
            border: 2px solid red
          "
        >
        <div
          id="circle"
          style="
            position: absolute;
            width: 10px;
            height: 10px;
            background-color: #000;
            border-radius: 50%;
          "
        ></div>
        <script>
         const box = document.getElementById("box");
         box.addEventListener("mousemove", event => {
           circle.style.top = `${event.clientY}px`;
           circle.style.left = `${event.clientX}px`;
         });
        </script>
      </body>
    </html>
    </script>
  </body>
</html>

📍결과

  • 커서가 네모 박스 안에 있을때 마우스오버시, 검정색 원이 커서를 따라다닌다. 
  • 마우스가 움직일때마다 원의 top과 left의 값이 바뀐다.

 


   resize

  • 창 크기가 바뀔때마다, 넓이와 높이값이 달라진다.

✏️입력

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <!DOCTYPE html>
    <html>
      <head>
        <title>Welcome</title>
      </head>
      <body>
        <script>
         window.addEventListener("resize", () => {
            document.body.innerText = `현재 창 크기는 ${window.
            innerWidth} x ${window.innerHeight}`;
         });
        </script>
      </body>
    </html>
    </script>
  </body>
</html>

📍결과

 

 

이벤트 type은 상당히 많다. 

관련된 type들을 사용해보면서 어떤 기능인지 연습을 해보기를 권한다.

 

 

 

자주 쓰는 EVENT type
click 클릭 시 이벤트 발생.
dblclick 더블클릭 시 이벤트 발생.
keydown 키보드를 뗐을 때 이벤트 발생
keyup 키보드를 입력했을 때 이벤트 발생
focus // input태그속성 입력창에 마우스를 눌렀을 때 발생
focusin // input태그속성  
blur // input태그속성 focus를 잃을 때 이벤트 발생
focusout/ / input태그속성  
mousemove 마우스를 움직일때마다 이벤트 발생
resize 창 크기가 바뀔 때마다, 너비와 높이값을 업데이트 해준다