LEARNING JAVASCRIPT - Trang 294

Now we see that propagation stops totally at the

<button>

capture, and no further

propagation occurs:

capture: BODY
capture: DIV (canceled)
capture: BUTTON (canceled)

addEventListener

replaces a much older way to add events: using

“on” properties. For example, a click handler would have been

added on the element elt with elt.onclick = function(evt)
{ /* handler */ }

. The primary disadvantage of this method is

that only one handler could be registered at a time.

While it is unlikely that you will have to do advanced control of event propagation

very often, it is a subject that causes much confusion among beginners. Having a firm

grasp on the details of event propagation will set you apart from the crowd.

With jQuery event listeners, explicitly returning false from the

handler is equivalent to calling stopPropagation; this is a jQuery

convention, and this shortcut does not work in the DOM API.

Event Categories

MDN has an excellent reference of all

DOM events grouped into categories

. Some

commonly used event categories include:
Drag events

Allow the implementation of a drag-and-drop interface with events like

drag

start

,

drag

,

dragend

,

drop

, and others.

Focus events

Allow you to take action when a user interacts with editable elements (such as

form fields).

focus

is raised when a user “enters” a field (by clicking, pressing

Tab, or touching), and

blur

is raised when the user “leaves” a field (by clicking

somewhere else, pressing Tab, or touching elsewhere). The

change

event is raised

when a user makes a change to a field.

Form events

When a user submits a form (by pressing a Submit button, or pressing Enter in

the right context), the

submit

event is raised on the form.

270 | Chapter 18: JavaScript in the Browser