What is an Event Object? Event Handlers and more

devfish·2023년 1월 6일
0

Javascript

목록 보기
16/30
post-thumbnail

3 ways of attaching behavior to an event

basic eventListener syntax
element.addEventListener("type-of-event", functiontoExecute)

  1. HTML: <element>
  2. JS: object.onclick=function(){myScript};
  3. JS: object.addEventListener("click", myScript);

2번과 3번의 차이: 2번의 경우 이벤트를 덮어씀, 3번의 경우 이벤트가 누적됨
IE 6,7,8에서는 addEventListener가 지원 안됨

이벤트 속성(onclick)에 이벤트 핸들러를 등록할 때에는 함수 그 자체로 등록해야 함. 함수 실행을 등록하는 것이 아님.

To pass arguments to addEventListener, you need to write it like this:

Event Object

event handler functions are passed an argument: the event object. This object holds additional information about the event. For example, if we want to know which mouse button was pressed, we can look at the event object’s button property. ~El. JS

stopPropagation

an event handler can call the stopPropagation method on the event object to prevent handlers further up from receiving the event. This can be useful when, for example, you have a button inside another clickable element and you don’t want clicks on the button to activate the outer element’s click behavior.

Propagation direction

outward, from the node where it happened to that node’s parent node and on to the root of the document. the more specific handler—the one on the button—gets to go first.

event bubbling vs capturing

The standard DOM Events describes 3 phases of event propagation:

Capturing phase – the event goes down to the element.
Target phase – the event reached the target element.
Bubbling phase – the event bubbles up from the element.

<!doctype html>
<body>
<style>
body * {
  margin: 10px;
  border: 1px solid blue;
}
</style>

<form>FORM
<div>DIV
  <p>P</p>
</div>
</form>

<script>
for(let elem of document.querySelectorAll('*')) {
  elem.addEventListener("click", e => alert(`Capturing: ${elem.tagName}`), true);
  elem.addEventListener("click", e => alert(`Bubbling: ${elem.tagName}`));
}
</script>
</body>

The code sets click handlers on every element in the document to see which ones are working. If you click on <p>, then the sequence is:

  • HTML → BODY → FORM → DIV -> P (capturing phase, the first listener)
  • P → DIV → FORM → BODY → HTML (bubbling phase, the second listener)

target property

Most event objects have a target property that refers to the node where they originated. You can use this property to ensure that you’re not accidentally handling something that propagated up from a node you do not want to handle.

if you have a node containing a long list of buttons, it may be more convenient to register a single click handler on the outer node and have it use the target property to figure out whether a button was clicked, rather than register individual handlers on all of the buttons

 <button>A</button>
<button>B</button>
<button>C</button>
<script>
 document.body.addEventListener("click", event => {
   if (event.target.nodeName == "BUTTON") {
     console.log("Clicked", event.target.textContent);
   }
 });
</script>
  • event.target.innerText
  • event.target.textContent

prevent default actions

Stops the default behavior associated with the event

  let link = document.querySelector("a");
  link.addEventListener("click", event => {
      console.log("Nope.");
      event.preventDefault();
  });

caution in using keydown

Fires every time the key repeats (held down)

The Event Loop

browser event handlers are scheduled when the event occurs, but must wait for all other scripts to finish running to fire. If the loop is occupied with other stuff, any interaction with the page has to wait until it's done processing what came before.

which is why web workers exist - so you can run time-consuming js stuff alongside the main script on its own timeline so it does not freeze the page.

let squareWorker = new Worker("code/squareworker.js");
squareWorker.addEventListener("message", event => {
	 console.log("The worker responded:", event.data);
});
squareWorker.postMessage(10);
squareWorker.postMessage(24);

event type

onchange: when the value of an HTML element is changed (via JS)


학습목표

  • 기초적인 event를 알고, event handler를 element에 적용할 수 있다.
  • onclick 에 직접 할당하는 것과 addEventListener의 차이를 이해한다.
  • eventHandler 함수를 만들고, eventHandler의 첫 번째 인자를 사용할 수 있다.

이벤트 객체에 대해서 더 자세히 알고 싶다면, 아래 키워드를 검색해서 학습

  • onsubmit
  • onchange
  • onmouseover
  • onkeyup
  • event.preventDefault
profile
la, di, lah

0개의 댓글