<script>
const onClickButton = () => {
console.log('버튼 클릭');
};
const $button = document.querySelector('button')
$button.addEventListener('click', onClickButton)
</script>
지정한 유형의 이벤트를 대상이 수신할 때마다 호출할 함수 설정하는 매서드.
구문
addEventListener(이벤트명, 실행할 함수명, 옵션)
이벤트명 : Javascript에서 발생할 수 있는 이벤트명
함수명 : 해당 이벤트가 발생할 때 실행할 함수명. 생략가능.
옵션 : 이벤트 수신기의 특징을 지정할 수 있는 객체.
*옵션에 대한 내용은 이 사이트(https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault)를 참조
<!doctype html>
<head>
<body>
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
<script>
// t2의 콘텐츠를 바꾸는 함수
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// 표에 이벤트 수신기 추가
const el = document.getElementById("outside");
el.addEventListener("click", mdoifyText, false);
</script>
</body>
</html>
해당 이벤트 리스너를 제거하는 기능
구문
romeve.EventListener(이벤트명, 함수, 옵션)
예시
*출처 : https://developer.mozilla.org/ko/docs/Web/API/EventTarget/removeEventListener
const body = document.querySelector('body')
const clickTarget = document.getElementById('click-target')
const mouseOverTarget = document.getElementById('mouse-over0target')
let toggle = false;
function makeBackgroundYellow() {
if (toggle) {
body.style.backgroundcolor = 'white';
} else {
body.style.backgroundColor = 'yellow';
}
toggle = !toggle;
}
clickTarget.addEventListener('click', makeBackgroundYellow, false);
mouseOverTarget.addEventListener('mouseover', function() {
clickTarget.removeEventListener('click', makeBackgroundYellow, false);
});