어트리뷰트 방식
<body>
<button id="btn" onclick="sayHi('User')">BTN</button> // 호출문
//sayHi 였다면, 함수 참조 였을 것
</body>
<script>
function sayHi(name) {
alert(`Hi ${name}`);
}
</script>
<button id="btn"hi"); console.log("user");">
이벤트 핸들러 프로퍼티 방식
<body>
<button id="btn" ">BTN</button>
</body>
<script>
const $btn = document.getElementById("btn");
$btn.onclick = function () {
alert(`Hi ${name}`);
};
</script>
$btn
: 이벤트 타겟onclick
: on + 이벤트 타입function () {}
: 이벤트 핸들러addEventListener 메서드 방식
<body>
<button id="btn" ">BTN</button>
</body>
<script>
const $btn = document.getElementById("btn");
$btn.addEventListener("click",function () {
alert(`Hi ${name}`);
})
</script>
EventTarget.addEventListener('eventType,eventHandler[,useCapture])
removeEventListener
로 제거할 수 있다.이벤트 핸들러의 첫 인자로 이벤트 객체가 전달된다.
event
를 줘야만 한다.event
를 인자로 받기 때문이다.생성자 함수를 가지는 객체이다.
이벤트 객체의 공통 프로퍼티들
MouseEvent
타입의 객체이다.KeyboardEvent
타입의 객체이다.window - document - html - body - ul - li를 클릭했을 경우
addEventListener을 제외하고는 타겟, 버블링 단계만 캐치한다.
대부분의 이벤트는 버블링단계에서 상위 DOM에서도 캐치가능하다.
event.preventDefault()
event.stopPropagation()
.onblur = () => sayHi(name)
.onblur = name => () => console.log('Hi ${name}')
키보드 커스텀 이벤트 생성: new KeyboardEvent(keyboard event)
새로운 타입의 커스텀 이벤트 생성: new CustomEvent(event type)
new CustomEvent(event type, {bubbles: true, cancelable: true})
이벤트 디스패치
Element.dispatchEvent(customEvent)
: