상추의 IT저장소

JS) 이벤트 핸들러 본문

Javascript

JS) 이벤트 핸들러

구너상추 2022. 11. 21. 17:52

이벤트란?

프로그래밍하고 있는 시스템에서 일어나는 사건 혹은 발생

 

마우스이벤트 타입

click 마우스 버튼을 클릭했을 때
dbclick 마우스 버튼을 더블 클릭했을 때
mousedown 마우스 버튼을 누르고 있을 때
mouseup 누르고 있던 마우스 버튼을 뗄 때
mousemove 마우스 커서를 움직일 때
mouseenter 마우스 커서를 HTML 요소 안으로 이동했을 때 (버블링 x)
mouseover 마우스 커서를 HTML 요소 안으로 이동했을 때 (버블링 o)
mouseleave 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링x)
mouseout 마우스 커서를 HTML 요소 밖으로 이동했을 때(버블링o)

 

이벤트 핸들러

각각의 이용가능한 이벤트들은 이벤트 핸들러를 가지고 있는데, 이는 이벤트가 발생되면 실행되는 코드블럭이다.

 

이벤트 핸들러를 등록하는 세가지 방식

1. 이벤트 핸들러 어트리뷰트 방식

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

3. addEventListener 메서드 방식

 

 

<body>
    <button onclick="sayHi('lettuce')">Click me!</button>
    <button class="here">Click here!!!</button>
    <button class="it">Click it!!!!!</button>
    <em></em>
    
    <script>
    //이벤트 핸들러 어트리뷰트 방식
      function sayHi(name) {
        console.log(`Hi! ${name}.`);
      }
      
    //이벤트 핸들러 프로퍼티 방식
      const here = document.querySelector('.here');

      here.onclick = function () {
        console.log("what the hell!!");
      }
      
    // addEventListener 메서드 방식
      const it = document.querySelector('.it');
      const em = document.querySelector('em');

      it.addEventListener("click", function () {
        em.innerHTML = "Button Clicked 1";
      })

    </script>
  </body>

결과>>

1. 첫번째 버튼 클릭

2. 두번째 버튼 클릭

 

3. 세번째 버튼 클릭

 

 

 

 

 

출처  :https://developer.mozilla.org/ko/docs/Learn/JavaScript/Building_blocks/Events

 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 여러분이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 여러분이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주

developer.mozilla.org

 

'Javascript' 카테고리의 다른 글

JS) Scope  (0) 2022.11.23
JS) 실행컨텍스트  (0) 2022.11.23
JS) node.js 개념 이해  (0) 2022.11.21
JS) Promise, async/await  (0) 2022.11.20
JS)Array.filter() Array.reduce()  (0) 2022.11.18