๐Ÿ‹ Event Handlers

hayoungยท2023๋…„ 3์›” 22์ผ
0

JavaScript-DOM

๋ชฉ๋ก ๋ณด๊ธฐ
4/5
post-thumbnail

1. ๐Ÿ˜†Mouse events

๋งˆ์šฐ์Šค ์ด๋ฒคํŠธ ์ข…๋ฅ˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
JavaScript event reference: MDN ์—์„œ ๋” ๋งŽ์€ ์ด๋ฒคํŠธ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

2. ๐Ÿ˜์ด๋ฒคํŠธ ํ•ธ๋“ค๋ง

const alertH1 = function (e) {
  alert("addEventListener1: you are reading the heading");
};

// h1์— mouse enter ์ผ ๋•Œ alertH1 ์‹คํ–‰
const h1 = document.querySelector("h1");
h1.addEventListener("mouseenter", alertH1);

// 5์ดˆ ํ›„ alertH1 ์‚ญ์ œ
setTimeout(() => h1.removeEventListener("mouseenter", alertH1), 5000);

// old way! ๊ณผ๊ฑฐ ๋ฐฉ๋ฒ•์ž„ ์‚ฌ์šฉ x (onclick ๋“ฑ๋“ฑ)
// h1.onmouseenter = function (e) {
//   alert("addEventListener2: you are reading the heading");
// };

๐Ÿฅ‘ ์™œ addEventListener๋ฅผ ๋” ๋งŽ์ด ์“ฐ๋Š”๊ฐ€?
1) We can add multiple event listners to the same event (old way will override the 1st function.)
2) We can remove an event handler in case we don't need it anymore.

profile
Persistence pays off.

0๊ฐœ์˜ ๋Œ“๊ธ€