쫑가 과정

Event(.addEventListener(), event Handler property) 본문

JavaScript/공부

Event(.addEventListener(), event Handler property)

쫑가 2021. 7. 17. 17:20
 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 당신이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 당신이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주는 것

developer.mozilla.org

무언가를 프로그래밍하고 있는 시스템에서 무언가 발생하는 거다.

예를 들어 글자를 마우스로 클릭했을 때 글자 색상이 변하는 식이다.

event 종류 찾아보기.

1. mdn

 

Event reference | MDN

This topic provides an index to the main sorts of events you might be interested in (animation, clipboard, workers etc.) along with the main classes that implement those sorts of events. At the end is a flat list of all documented events.

developer.mozilla.org

굉장히 많은 events가 있다.

이 페이지에는 웹에서 접할 수 있는 일반적인 이벤트가 나열되어있다. 

 

내가 원하는 event를 검색하고 싶다면 web APIs 문장이 포함된 페이지를 찾는다.

javascript관점의 HTML Heading Element란 의미이다.

HTML Heading Element는 HTML Element이다.

검색해서 HTML Element를 살펴보자. 다양한 property들을 볼 수 있다.

2. console.dir()

<body>
    <div class="todo-list">
        <h1>a</h1>
        <h1>b</h1>
        <h1>c</h1>
        <h1>d</h1>
        <h1>e</h1>
    </div>
    <script src="app.js"></script>
</body>
const todo = document.querySelector(".todo-list h1:first-child");
console.dir(todo);

console.dir()을 작동시켜 console에서

property를 보면 on으로 시작하는 것이 다 event이다.

onabort, onfocus, onclick 등 사용할 때는 on을 빼고 써야 한다.

사용하는 방법

1.addEventListener()

 

EventTarget.addEventListener() - Web API | MDN

EventTarget의 addEventListener() 메서드는 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정합니다.

developer.mozilla.org

형태)

target.addEventListener(type, listener[, options]);

type : event 유형

listener : event가 실행될 때 무언가를 해주는 객체 (EventListener interface 또는 JavaScript function)

 

예시)

const todo = document.querySelector(".todo-list h1:first-child");
console.dir(todo);

function handleTodoClick() {
    todo.style.color = "blue";
}
function handleTodoEnter() {
    todo.innerText = "Mouse is here!";
}
function handleTodoLeave() {
    todo.innerText = "Mouse is gone!";
}

todo.addEventListener("click", handleTodoClick);
todo.addEventListener("mouseenter", handleTodoEnter);
todo.addEventListener("mouseleave", handleTodoLeave);

 

todo를 click 했을 때(type) handleTodoClick(listener)이 작동.

todo를 mouseenter 했을 때(type) handleTodoEnter(listener)이 작동.

todo를 mouseleave 했을 때(type) handleTodoLeave(listener)이 작동.

2. event Handler property

 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 당신이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 당신이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주는 것

developer.mozilla.org

위에서 봤던 on으로 시작하는 event property다.

형태)

target.eventHandlerProperty = function;

색상을 바꾸기 위해 사용한 형태와 같다.

title.style.color = "blue"

 

예시)

const todo = document.querySelector(".todo-list h1:first-child");
console.dir(todo);

function handleTodoClick() {
    todo.style.color = "blue";
}
function handleTodoEnter() {
    todo.innerText = "Mouse is here!";
}
function handleTodoLeave() {
    todo.innerText = "Mouse is gone!";
}
todo.onclick = handleTodoClick;
todo.onmouseenter = handleTodoEnter;
todo.onmouseleave = handleTodoLeave;

결과는 같다.

두 가지 중 어떤 것을 사용할지는 본인 선택이다.

링크로 들어가면 장, 단점을 잘 말해주니까 읽어보자.

 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 당신이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 당신이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주는 것

developer.mozilla.org

 

addEventListener()가 활용하기 좋은 기능들이 많다.

 

지금까지는 HTML element에 실행하는 event를 해봤는데 다른 target도 하나 해보자.

window

 

Window - Web API | MDN

Window 인터페이스는 DOM 문서를 담은 창을 나타냅니다.

developer.mozilla.org

todo는 HTML element이고,

window는 document처럼 기본적으로 제공해준다.

const todo = document.querySelector(".todo-list h1:first-child");
console.dir(todo);

function handleWindowResize() {
    document.body.style.backgroundColor = "tomato"
}

window.addEventListner("resize", handleWindowResize);

 

 document.body.style.backgroundColor = "tomato"

html, head, body태그는 특별하기 때문에 property로 사용 가능하다.

다른 태그들을 선택하려면 querySelector처럼 선택자를 사용해야 한다.

target이 window라서 윈도 창 크기를 변경했을 때(event) 배경 색상이 변경됐다.

Comments