브라우저는 처리해야 할 특정 사건(클릭, 키보드 입력)이 발생하면 이를 감지하여 이벤트를 발생시킨다.
이벤트 핸들러 : 이벤트가 발생했을 때 호출될 함수.
이벤트 핸들러 등록 : 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 의미한다.
이벤트 타입 : 이벤트의 종류를 나타내는 문자열이다.
예시 ) 'click', 'keyup', 'input'
이벤트 핸들러 속성의 이름 : 'on' + 이벤트의 종류.
단점 : HTML과 자바스크립트가 뒤섞이는 문제점이 있다.
<!DOCTYPE>
<html>
<body>
<button onclick="Hello('Jennie')">Click!</button>
<!-- <button> 요소의 속성으로 이벤트 지정-->
<script>
function Hello(name){
console.log(`Hello, ${name}!`);
}
</script>
</body>
</html>
window 객체와 Document, HTMLElement 타입의 DOM 노드 객체는 이벤트에
대응하는 이벤트 핸들러 프로퍼티를 갖고 있다.
장점 : 1번 방식의 문제점을 해결할 수 있다.
단점 : 이벤트 핸들러 프로퍼티에 하나의 이벤트 핸들러만 바인딩할 수 있다.
<!DOCTYPE html>
<html>
<body>
<button>Click!</button>
<script>
const $button = document.querySelector('button');
$button.onclick = function() {
console.log('button click');
};
</script>
</body>
</html>
addEventListener
메서드 방식addEventListener
메서드 방식을 사용하는 것을 권장한다.<!DOCTYPE html>
<html>
<body>
<button>Click!</button>
<script>
const $button = document.querySelector('button');
$button.addEventListener('click',function(){
console.log('button click');
});
</script>
</body>
</html>