click : 클릭했을 때dbclick : 더블 클릭했을 때mousedown : 버튼 눌렀을 때mouseup : 누르고 있던 버튼을 놓았을 때mousemove : 커서를 움직였을 때mouseenter : HTML 요소 안으로 이동했을 때 (버블링 되지 않음)mouseover : HTML 요소 안으로 이동했을 떄 (버블링 됨)mouseleave : HTMl 요소 밖으로 이동했을 때 (버블링 되지 않음)mouseout : HTML 요소 밖으로 이동했을 때 (버블링 됨)keydown : 모든 키를 눌렀을 때 keyup : 누르고 있던 키를 놓았을 때 한 번만 발생keydown과 동일함keypress : 문자 키를 눌렀을 때 연속적으로 발생focus : HTML 요소가 포커스를 받았을 때 (버블링되지 않음)blur : HTML 요소가 포커스를 잃었을 때 (버블링 됨)focusin : HTML 요소가 포커스를 받았을 때 (버블링되지 않음)focusout : HTML 요소가 포커스를 잃었을 때 (버블링 됨)focusin / focusout를 이벤트 핸들러 프로퍼티 방식으로 등록 시 정상 동작하지 않는 경우 있음addEventListener 메서드 방식으로 등록해야 함submit input, select 입력 필드에서 엔터 키를 눌렀을 때submit 버튼을 클릭했을 때reset : form 요소 내의 reset 버튼을 클릭했을 때input : input 요소 값이 입력되었을 때change : input 요소 값이 변경되었을 때readystatechange : HTML 문서의 로드와 파싱 상태를 나타내는 document.readyState 프로퍼티 값이 변경될 때document.readyState : loading, interactive, completeDOMContentLoaded : HTML 문서의 로드와 파싱이 완료되어 DOM 생성이 완료되었을 때resize : 브라우저 윈도우 크기를 리사이즈할 때 연속적으로 발생window 객체에서만 발생함scroll : 웹페이지 또는 HTML 요소를 스크롤할 때 연속적으로 발생load : DOMContentLoaded 이벤트 발생 이후, 모든 리소스 로딩이 완료되었을 때unload : 리소스가 언로드될 때 (주로 새로운 웹페이지를 요청한 경우)abort : 리소스 로딩이 중단되었을 때error : 리소스 로딩을 실패했을 때onclick)<button onClick="sayHi('Lee')">Click!</button>
// 이벤트 핸들러 어트리뷰트 이름과 동일한 이름으로 암묵적으로 생성되는 이벤트 핸들러의 함수 몸체
function onClick(event) {
sayHi('Lee');
}
$button)onclick)function)$button.onclick = function () {
console.log('button click');
};EventTarget.prototype.addEventListener 메서드EventTarget.addEventListener('eventType', functionName[, useCapture])$button.addEventListener('click', function () {
console.log('button click');
});EventTarget.prototype.removeEventListeneraddEventListener로 등록한 이벤트 핸들러 제거addEventListener에 전달한 인수와 일치하지 않으면 핸들러가 제거되지 않음argument.callee을 사용하여 제거할 수 있음 -> 권장하지 않음 $button.onclick = null;event'로 지정해야 함
Event.protytpe) : 모든 이벤트 객체가 상속받는 공통 프로퍼티type (string) : 이벤트 타입target (DOM node) : 이벤트를 발생시킨 DOM 요소currentTarget (DOM node) : 이벤트 핸들러가 바인딩된 DOM 요소eventPhase (number) : 이벤트 전파 단계bubbles (boolean) : 이벤트 버블링 전파 여부cancelable (boolean) : preventDefault 사용 가능 여부defaultPrevented (boolean) : preventDefault 사용 여부isTrusted (boolean) : 사용자 행위에 의해 발생한 이벤트 여부timeStamp (number) : 이벤트 발생 시각target 프로퍼티와 currentTarget 프로퍼티는 동일한 DOM 요소를 가리킴MouseEvent)의 고유 프로퍼티screenX/screenY, clientX/clientY, pageX/pageY, offsetX/offsetYaltKey, ctrlKey, shiftKey, buttonKeyboardEvent)의 고유 프로퍼티altKey, ctrlKey, shiftKey, metaKey, key, keyCode 등keyup : 한글 입력 후 엔터 키 누르면 이벤트 핸들러가 두 번 호출되는 현상 발생keydown 이벤트 사용 권장addEventListener 방식은 3단계 모두 캐치 가능 -> 3번째 인수 trueEvent.prototype.composedPath로 확인 가능)focus/blur/load/unload/abort/error/mouseenter/mouseleave) -> 캡처링에서 캐치Element.prototype.matches 메서드로 특정 노드인지 확인 가능target과 currentTarget 프로퍼티가 다를 수 있음a > href 링크로 이동, checkbox/radio > 체크 및 해제 등preventDefault : 기본 동작 중단stopPropagation : 이벤트 전파 중지this는 전역 객체 windowthis는 전역 객체를 가리킴this는 이벤트를 바인딩한 DOM 요소를 가리킴 <button onclick="handleClick(this)"> Click </button>
<script>
function handleClick(button) {
console.log(button); // button 요소
console.log(this); // window
}
</script>
addEventListener 방식의 this는 이벤트를 바인딩한 DOM 요소this === 이벤트 객체의 currentTarget 프로퍼티this가 생성할 인스턴스를 가리키려면bind 메서드 사용this는 상위 스코프의 this 이므로constructor() {
this.$button = document.querySelector('.btn');
this.count = 0;
// increase 메서드 내부의 this에 생성할 인스턴스를 바인딩함
this.$button.onclick = this.increase.bind(this);
}
increase() {
this.$button.textContent = ++this.count;
}
// 또는 .bind 없이 화살표 함수 가능
increase = () => this.$button.textContent = ++this.count;
addEventListener 방식은 함수 자체 등록해야 함// 1. 함수를 호출하면서 인수 전달
// 인수가 없는 경우 $input.onblur = checkTextLength;
$input.onblur = () => checkTextLength(10);
// 2. 이벤트 핸들러를 반환하는 함수를 호출하면서 인수 전달
const checkTextLength = min => e =>
$msg.textContent
= $input.value.length < min ? `${min}자 이상 입력해주세요` : '';
$input.onblur = checkTextLength(10)
CustomEvent 이벤트 생성자 함수 사용const customEvent = new CustomEvent('example');bubbles, cancelable = false 기본 설정isTrusted = falseisTrusted = truedispatchEvent : 이벤트 객체를 인수로 전달하면서 호출하면 커스텀 이벤트가 발생함addEventListener 방식으로 등록해야 함[출처] 모던 자바스크립트, Deep Dive