addEventListener() 메서드는 타겟 요소에서 특정 이벤트가 발생했을 때 어떤 함수가 실행될지를 설정합니다. 타겟 요소는 주로 HTML 요소, Document, 또는 Window입니다.
addEventListener() 메서드의 Syntax:
eventTarget.addEventListener('eventType', listener)
eventType의 대표적인 예시로는 click, load, scroll과 키보드 관련 이벤트, 마우스 관련 이벤트들이 있습니다.
다음은 addEventListener()를 사용한 예시 코드입니다.
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>addEventListener()</title> </head> <body> <h1>h1</h1> <div id="info">Information</div> <script src="app.js"></script> </body> </html>
const title = document.querySelector("h1"); console.log(title); function handleTitleClick() { title.style.color = "blue"; } title.addEventListener("click", handleTitleClick); const info = document.querySelector("#info"); function handleWindowResize() { info.textContent = window.innerWidth; } window.addEventListener("resize", handleWindowResize);
addEventListener() 메서드에 listener에 해당하는 함수를 전달할 때는, 그 함수 자체를 전달하는 것이기 때문에 괄호를 붙이지 않아야 합니다.
* addEventListener() 메서드와 반대의 동작을 하는 removeEventListener() 메서드도 존재합니다. addEventListener() 메서드로 추가한 내용을 반대로 삭제하는 역할을 합니다.
728x90
반응형
'Frontend > Javascript' 카테고리의 다른 글
[JavaScript] <script> 태그의 위치 (0) | 2024.02.12 |
---|---|
[JavaScript] toggle() 메서드 (0) | 2024.02.04 |
[JavaScript] console.dir() 메서드 (0) | 2024.01.31 |
[JavaScript] getElement* 와 querySelector (0) | 2024.01.31 |
[JavaScript] every(), some() 메서드 (0) | 2023.09.11 |