1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
|
---
title: Introducción a eventos
slug: Learn/JavaScript/Building_blocks/Events
translation_of: Learn/JavaScript/Building_blocks/Events
original_slug: Learn/JavaScript/Building_blocks/Eventos
---
<div>{{LearnSidebar}}</div>
<div>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}</div>
<p class="summary">Los eventos son acciones u ocurrencias que suceden en el sistema que está programando y que el sistema le informa para que pueda responder de alguna manera si lo desea. Por ejemplo, si el usuario hace clic en un botón en una página web, es posible que desee responder a esa acción mostrando un cuadro de información. En este artículo, discutiremos algunos conceptos importantes que rodean los eventos y veremos cómo funcionan en los navegadores. Este no será un estudio exhaustivo; solo lo que necesitas saber en esta etapa.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Prerrequisitos:</th>
<td>Conocimientos básicos de informática, entendimiento básico de HTML y CSS, <a href="https://developer.mozilla.org/es/docs/Learn/JavaScript/First_steps">Primeros pasos con JavaScript</a>.</td>
</tr>
<tr>
<th scope="row">Objetivo:</th>
<td>Comprender la teoría fundamental de los eventos, cómo funcionan en los navegadores y cómo los eventos pueden diferir en distintos entornos de programación.</td>
</tr>
</tbody>
</table>
<h2 id="Una_serie_de_eventos_afortunados">Una serie de eventos afortunados</h2>
<p>Como se mencionó anteriormente, los <strong>eventos</strong> son acciones u ocurrencias que suceden en el sistema que está programando — el sistema disparará una señal de algún tipo cuando un evento ocurra y también proporcionará un mecanismo por el cual se puede tomar algún tipo de acción automáticamente (p.e., ejecutando algún código) cuando se produce el evento. Por ejemplo, en un aeropuerto cuando la pista está despejada para que despegue un avión, se comunica una señal al piloto y, como resultado, comienzan a pilotar el avión.</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/14077/MDN-mozilla-events-runway.png" style="display: block; margin: 0px auto;"></p>
<p>En el caso de la Web, los eventos se desencadenan dentro de la ventana del navegador y tienden a estar unidos a un elemento específico que reside en ella — podría ser un solo elemento, un conjunto de elementos, el documento HTML cargado en la pestaña actual o toda la ventana del navegador. Hay muchos tipos diferentes de eventos que pueden ocurrir, por ejemplo:</p>
<ul>
<li>El usuario hace clic con el mouse sobre un elemento determinado o coloca el cursor sobre un elemento determinado.</li>
<li>El usuario presiona una tecla en el teclado.</li>
<li>El usuario cambia el tamaño o cierra la ventana del navegador.</li>
<li>Una página web termina de cargar.</li>
<li>Un formulario se envía</li>
<li>Un video se reproduce, pausa o finaliza la reproducción.</li>
<li>Un error ocurre.</li>
</ul>
<p>Se deducirá de esto (y echar un vistazo a MDN <a href="https://developer.mozilla.org/es/docs/Web/Events">Referencia de eventos</a>) que hay <strong>muchos</strong> eventos a los que se puede responder.</p>
<p>Cada evento disponible tiene un <strong>controlador de eventos</strong>, que es un bloque de código (generalmente una función JavaScript definida por el usuario) que se ejecutará cuando se active el evento. Cuando dicho bloque de código se define para ejecutarse en respuesta a un disparo de evento, decimos que estamos <strong>registrando un controlador de eventos</strong>. Tenga en cuenta que los controladores de eventos a veces se llaman <strong>oyentes de eventos</strong> — son bastante intercambiables para nuestros propósitos, aunque estrictamente hablando, trabajan juntos. El oyente escucha si ocurre el evento y el controlador es el código que se ejecuta en respuesta a que ocurra.</p>
<div class="note">
<p><strong>Nota</strong>: Es útil tener en cuenta que los eventos web no son parte del lenguaje central de JavaScript: se definen como parte de las API integradas en el navegador.</p>
</div>
<h3 id="Un_ejemplo_simple">Un ejemplo simple</h3>
<p>Veamos un ejemplo simple para explicar lo que queremos decir aquí. Ya has visto eventos y controladores de eventos en muchos de los ejemplos de este curso, pero vamos a recapitular solo para consolidar nuestro conocimiento. En el siguiente ejemplo, tenemos un solo {{htmlelement ("button")}}, que cuando se presiona, hará que el fondo cambie a un color aleatorio:</p>
<pre class="brush: html notranslate"><button>Cambiar color</button></pre>
<div class="hidden">
<pre class="brush: css notranslate">button { margin: 10px };</pre>
</div>
<p>El JavaScript se ve así:</p>
<pre class="brush: js notranslate">const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.onclick = function() {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}</pre>
<p>En este código, almacenamos una referencia al botón dentro de una variable llamada <code>btn</code>, usando la función {{domxref ("Document.querySelector ()")}}. También definimos una función que devuelve un número aleatorio. La tercera parte del código es el controlador de eventos. La variable <code>btn</code> apunta a un elemento <code><button></code>, y este tipo de objeto tiene una serie de eventos que pueden activarse y, por lo tanto, los controladores de eventos están disponibles. Estamos escuchando el disparo del evento "click", estableciendo la propiedad del controlador de eventos <code>onclick</code> para que sea igual a una función anónima que contiene código que generó un color RGB aleatorio y establece el <code><body></code> color de fondo igual a este.</p>
<p>Este código ahora se ejecutará cada vez que se active el evento "click" en el elemento <code><button></code>, es decir, cada vez que un usuario haga clic en él.</p>
<p>El resultado de ejemplo es el siguiente:</p>
<p>{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}</p>
<h3 id="No_son_solo_páginas_web">No son solo páginas web</h3>
<p>Otra cosa que vale la pena mencionar en este punto es que los eventos no son particulares de JavaScript — la mayoría de los lenguajes de programación tienen algún tipo de modelo de eventos, y la forma en que funciona a menudo diferirá de la forma en que funciona en JavaScript. De hecho, el modelo de eventos en JavaScript para páginas web difiere del modelo de eventos para JavaScript, ya que se utiliza en otros entornos.</p>
<p>Por ejemplo, <a href="/en-US/docs/Learn/Server-side/Express_Nodejs">Node.js</a> es un entorno en tiempo de ejecución de JavaScript muy popular que permite a los desarrolladores usar JavaScript para crear aplicaciones de red y del lado del servidor. El <a href="https://nodejs.org/docs/latest-v5.x/api/events.html">modelo de eventos de Node.js</a> se basa en que los oyentes (<em>listeners</em>) escuchen eventos y los emisores (<em>emitters</em>) emitan eventos periódicamente — no suena tan diferentes, pero el código es bastante diferente, haciendo uso de funciones como <code>on()</code> para registrar un oyente de eventos, y <code>once()</code> para registrar un oyente de eventos que anula el registro después de que se haya ejecutado una vez. The <a href="https://nodejs.org/docs/latest-v8.x/api/http.html#http_event_connect">documentos de eventos de conexión HTTP</a> proporcionan un buen ejemplo de uso.</p>
<p>Como otro ejemplo, ahora también puede usar JavaScript para crear complementos de navegadores — mejoras de funcionalidad del navegador — utilizando una tecnología llamada <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions">WebExtensions</a>. El modelo de eventos es similar al modelo de eventos web, pero un poco diferente — las propiedades de los oyentes de eventos se escriben en <em>camel-case</em> (ej. <code>onMessage</code> en lugar de <code>onmessage</code>), y deben combinarse con la función <code>addListener</code>. Consulte la página <a href="/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Examples">runtime.onMessage </a>para ver un ejemplo.</p>
<p>No necesita comprender nada sobre otros entornos en esta etapa de su aprendizaje; solo queríamos dejar en claro que los eventos pueden diferir en diferentes entornos de programación.</p>
<h2 id="Diferentes_formas_de_uso_de_eventos">Diferentes formas de uso de eventos</h2>
<p>Hay muchas maneras distintas en las que puedes agregar event listeners a los sitios web, que se ejecutara cuando el evento asociado se dispare. En esta sección, revisaremos los diferentes mecanismos y discutiremos cuales deberias usar..</p>
<h3 id="Propiedades_de_manejadores_de_eventos">Propiedades de manejadores de eventos</h3>
<p>Estas son las propiedades que existen, que contienen codigo de manejadores de eventos(Event Handler) que vemos frecuentemente durante el curso.. Volviendo al ejemplo de arriba:</p>
<pre class="brush: js notranslate">var btn = document.querySelector('button');
btn.onclick = function() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}</pre>
<p>La propiedad <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onclick">onclick</a></code> es la propiedad del manejador de eventos que está siendo usada en esta situación. Es escencialmente una propiedad como cualquier otra disponible en el botón (por ejemplo: <code><a href="/en-US/docs/Web/API/Node/textContent">btn.textContent</a></code>, or <code><a href="/en-US/docs/Web/API/HTMLElement/style">btn.style</a></code>), pero es de un tipo especial — cuando lo configura para ser igual a algún código, ese código se ejecutará cuando el evento se dispare en el botón.</p>
<p>You could also set the handler property to be equal to a named function name (like we saw in <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a>). The following would work just the same:</p>
<pre class="brush: js notranslate">var btn = document.querySelector('button');
function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
btn.onclick = bgChange;</pre>
<p>There are many different event handler properties available. Let's do an experiment.</p>
<p>First of all, make a local copy of <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/random-color-eventhandlerproperty.html">random-color-eventhandlerproperty.html</a>, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing <code>btn.onclick</code> to the following different values in turn, and observing the results in the example:</p>
<ul>
<li><code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onfocus">btn.onfocus</a></code> and <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onblur">btn.onblur</a></code> — The color will change when the button is focused and unfocused (try pressing tab to tab on to the button and off again). These are often used to display information about how to fill in form fields when they are focused, or display an error message if a form field has just been filled in with an incorrect value.</li>
<li><code><a href="/en-US/docs/Web/API/GlobalEventHandlers/ondblclick">btn.ondblclick</a></code> — The color will change only when it is double-clicked.</li>
<li><code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onkeypress">window.onkeypress</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onkeydown">window.onkeydown</a></code>, <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onkeyup">window.onkeyup</a></code> — The color will change when a key is pressed on the keyboard. <code>keypress</code> refers to a general press (button down and then up), while <code>keydown</code> and <code>keyup</code> refer to just the key down and key up parts of the keystroke, respectively. Note that it doesn't work if you try to register this event handler on the button itself — we've had to register it on the <a href="/en-US/docs/Web/API/Window">window</a> object, which represents the entire browser window.</li>
<li><code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onmouseover">btn.onmouseover</a></code> and <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onmouseout">btn.onmouseout</a></code> — The color will change when the mouse pointer is moved so it begins hovering over the button, or when it stops hovering over the button and moves off of it, respectively.</li>
</ul>
<p>Some events are very general and available nearly anywhere (for example an <code>onclick</code> handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use <a href="/en-US/docs/Web/API/GlobalEventHandlers/GlobalEventHandlers.onplay">onplay</a> only on specific elements, such as {{htmlelement("video")}}).</p>
<h3 id="Inline_event_handlers_—_dont_use_these">Inline event handlers — don't use these</h3>
<p>You might also see a pattern like this in your code:</p>
<pre class="brush: html notranslate"><button onclick="bgChange()">Press me</button>
</pre>
<pre class="brush: js notranslate">function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}</pre>
<div class="note">
<p><strong>Note</strong>: You can find the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/random-color-eventhandlerattributes.html">full source code</a> for this example on GitHub (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/random-color-eventhandlerattributes.html">see it running live</a>).</p>
</div>
<p>The earliest method of registering event handlers found on the Web involved <strong>event handler HTML attributes</strong> (aka <strong>inline event handlers</strong>) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:</p>
<pre class="brush: html notranslate"><button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button></pre>
<p>You'll find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.</p>
<p>For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.</p>
<p>Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:</p>
<pre class="brush: js notranslate">var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = bgChange;
}</pre>
<p class="brush: js">Note that another option here would be to use the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach()</a></code> built-in method available on all Array objects:</p>
<pre class="brush: js notranslate">buttons.forEach(function(button) {
button.onclick = bgChange;
});</pre>
<div class="note">
<p><strong>Note</strong>: Separating your programming logic from your content also makes your site more friendly to search engines.</p>
</div>
<h3 id="addEventListener_and_removeEventListener">addEventListener() and removeEventListener()</h3>
<p>The newest type of event mechanism is defined in the <a href="https://www.w3.org/TR/DOM-Level-2-Events/">Document Object Model (DOM) Level 2 Events</a> Specification, which provides browsers with a new function — <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>. This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:</p>
<pre class="brush: js notranslate">var btn = document.querySelector('button');
function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
btn.addEventListener('click', bgChange);</pre>
<div class="note">
<p><strong>Note</strong>: You can find the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/random-color-addeventlistener.html">full source code</a> for this example on GitHub (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/random-color-addeventlistener.html">see it running live</a>).</p>
</div>
<p>Inside the <code>addEventListener()</code> function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the <code>addEventListener()</code> function, in an anonymous function, like this:</p>
<pre class="brush: js notranslate">btn.addEventListener('click', function() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
});</pre>
<p>This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, <code><a href="/en-US/docs/Web/API/EventTarget/removeEventListener">removeEventListener()</a></code>, which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:</p>
<pre class="brush: js notranslate">btn.removeEventListener('click', bgChange);</pre>
<p>This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you've got to do is add/remove event handlers as appropriate.</p>
<p>Second, you can also register multiple handlers for the same listener. The following two handlers would not be applied:</p>
<pre class="brush: js notranslate">myElement.onclick = functionA;
myElement.onclick = functionB;</pre>
<p>As the second line would overwrite the value of <code>onclick</code> set by the first. This would work, however:</p>
<pre class="brush: js notranslate">myElement.addEventListener('click', functionA);
myElement.addEventListener('click', functionB);</pre>
<p>Both functions would now run when the element is clicked.</p>
<p>In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code> and <code><a href="/en-US/docs/Web/API/EventTarget/removeEventListener">removeEventListener()</a></code> reference pages.</p>
<h3 id="What_mechanism_should_I_use">What mechanism should I use?</h3>
<p>Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.</p>
<p>The other two are relatively interchangeable, at least for simple uses:</p>
<ul>
<li>Event handler properties have less power and options, but better cross-browser compatibility (being supported as far back as Internet Explorer 8). You should probably start with these as you are learning.</li>
<li>DOM Level 2 Events (<code>addEventListener()</code>, etc.) are more powerful, but can also become more complex and are less well supported (supported as far back as Internet Explorer 9). You should also experiment with these, and aim to use them where possible.</li>
</ul>
<p>The main advantages of the third mechanism are that you can remove event handler code if needed, using <code>removeEventListener()</code>, and you can add multiple listeners of the same type to elements if required. For example, you can call <code>addEventListener('click', function() { ... })</code> on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:</p>
<pre class="brush: js notranslate">element.onclick = function1;
element.onclick = function2;
etc.</pre>
<div class="note">
<p><strong>Note</strong>: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example <code>jQuery</code>) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.</p>
</div>
<h2 id="Other_event_concepts">Other event concepts</h2>
<p>In this section, we will briefly cover some advanced concepts that are relevant to events. It is not important to understand these fully at this point, but it might serve to explain some code patterns you'll likely come across from time to time.</p>
<h3 id="Event_objects">Event objects</h3>
<p>Sometimes inside an event handler function, you might see a parameter specified with a name such as <code>event</code>, <code>evt</code>, or simply <code>e</code>. This is called the <strong>event object</strong>, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:</p>
<pre class="brush: js notranslate">function bgChange(e) {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
e.target.style.backgroundColor = rndCol;
console.log(e);
}
btn.addEventListener('click', bgChange);</pre>
<div class="note">
<p><strong>Note</strong>: You can find the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/random-color-eventobject.html">full source code</a> for this example on GitHub (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/random-color-eventobject.html">see it running live</a>).</p>
</div>
<p>Here you can see that we are including an event object, <strong>e</strong>, in the function, and in the function setting a background color style on <code>e.target</code> — which is the button itself. The <code>target</code> property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.</p>
<div class="note">
<p><strong>Note</strong>: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. <code>e</code>/<code>evt</code>/<code>event</code> are most commonly used by developers because they are short and easy to remember. It's always good to stick to a standard.</p>
</div>
<p><code>e.target</code> is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as <code>e.target</code>, rather than having to select it in some more difficult way. In the following example (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/useful-eventtarget.html">useful-eventtarget.html</a> for the full source code; also see it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/useful-eventtarget.html">running live</a> here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an <code>onclick</code> handler to each that makes it so that a random color is applied to each one when clicked:</p>
<pre class="brush: js notranslate">var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].onclick = function(e) {
e.target.style.backgroundColor = bgChange();
}
}</pre>
<p>The output is as follows (try clicking around on it — have fun):</p>
<div class="hidden">
<h6 id="Hidden_example">Hidden example</h6>
<pre class="brush: html notranslate"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Useful event target example</title>
<style>
div {
height: 100px;
width: 25%;
float: left;
}
</style>
</head>
<body>
<script>
for (var i = 1; i <= 16; i++) {
var myDiv = document.createElement('div');
myDiv.style.backgroundColor = "red";
document.body.appendChild(myDiv);
}
function random(number) {
return Math.floor(Math.random()*number);
}
function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
return rndCol;
}
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].onclick = function(e) {
e.target.style.backgroundColor = bgChange();
}
}
</script>
</body>
</html></pre>
</div>
<p>{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}</p>
<p>Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object (see the {{domxref("Event")}} object reference for a full list). Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The <a href="/en-US/docs/Web/API/MediaRecorder_API">Media Recorder API</a>, for example, has a <code>dataavailable</code> event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding <a href="/en-US/docs/Web/API/MediaRecorder/ondataavailable">ondataavailable</a> handler's event object has a <code>data</code> property available containing the recorded audio or video data to allow you to access it and do something with it.</p>
<h3 id="Preventing_default_behavior">Preventing default behavior</h3>
<p>Sometimes, you'll come across a situation where you want to stop an event doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behaviour is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)</p>
<p>The trouble comes when the user has not submitted the data correctly — as a developer, you'll want to stop the submission to the server and give them an error message telling them what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.</p>
<p>First, a simple HTML form that requires you to enter your first and last name:</p>
<pre class="brush: html notranslate"><form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text">
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text">
</div>
<div>
<input id="submit" type="submit">
</div>
</form>
<p></p></pre>
<div class="hidden">
<pre class="brush: css notranslate">div {
margin-bottom: 10px;
}
</pre>
</div>
<p>Now some JavaScript — here we implement a very simple check inside an <a href="/en-US/docs/Web/API/GlobalEventHandlers/onsubmit">onsubmit</a> event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the <code><a href="/en-US/docs/Web/API/Event/preventDefault">preventDefault()</a></code> function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:</p>
<pre class="brush: js notranslate">var form = document.querySelector('form');
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
var submit = document.getElementById('submit');
var para = document.querySelector('p');
form.onsubmit = function(e) {
if (fname.value === '' || lname.value === '') {
e.preventDefault();
para.textContent = 'You need to fill in both names!';
}
}</pre>
<p>Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is ok for example purposes. The output is as follows:</p>
<p>{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}</p>
<div class="note">
<p><strong>Note</strong>: for the full source code, see <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/preventdefault-validation.html">preventdefault-validation.html</a> (also see it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/preventdefault-validation.html">running live</a> here.)</p>
</div>
<h3 id="Event_bubbling_and_capture">Event bubbling and capture</h3>
<p>The final subject to cover here is something that you'll not come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box.html">show-video-box.html</a> example in a new tab (and the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/show-video-box.html">source code</a> in another tab.) It is also available live below:</p>
<div class="hidden">
<h6 id="Hidden_video_example">Hidden video example</h6>
<pre class="brush: html notranslate"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Show video box example</title>
<style>
div {
position: absolute;
top: 50%;
transform: translate(-50%,-50%);
width: 480px;
height: 380px;
border-radius: 10px;
background-color: #eee;
background-image: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,0.1));
}
.hidden {
left: -50%;
}
.showing {
left: 50%;
}
div video {
display: block;
width: 400px;
margin: 40px auto;
}
</style>
</head>
<body>
<button>Display video</button>
<div class="hidden">
<video>
<source src="https://raw.githubusercontent.com/mdn/learning-area/master/javascript/building-blocks/events/rabbit320.mp4" type="video/mp4">
<source src="https://raw.githubusercontent.com/mdn/learning-area/master/javascript/building-blocks/events/rabbit320.webm" type="video/webm">
<p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
</video>
</div>
<script>
var btn = document.querySelector('button');
var videoBox = document.querySelector('div');
var video = document.querySelector('video');
btn.onclick = function() {
displayVideo();
}
function displayVideo() {
if(videoBox.getAttribute('class') === 'hidden') {
videoBox.setAttribute('class','showing');
}
}
videoBox.addEventListener('click',function() {
videoBox.setAttribute('class','hidden');
});
video.addEventListener('click',function() {
video.play();
});
</script>
</body>
</html></pre>
</div>
<p>{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}</p>
<p>This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:</p>
<pre class="brush: html notranslate"><button>Display video</button>
<div class="hidden">
<video>
<source src="rabbit320.mp4" type="video/mp4">
<source src="rabbit320.webm" type="video/webm">
<p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
</video>
</div></pre>
<p>When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <code><div></code> from <code>hidden</code> to <code>showing</code> (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):</p>
<pre class="brush: js notranslate">btn.onclick = function() {
videoBox.setAttribute('class', 'showing');
}</pre>
<p>We then add a couple more <code>onclick</code> event handlers — the first one to the <code><div></code> and the second one to the <code><video></code>. The idea is that when the area of the <code><div></code> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.</p>
<pre class="brush: js notranslate">videoBox.onclick = function() {
videoBox.setAttribute('class', 'hidden');
};
video.onclick = function() {
video.play();
};</pre>
<p>But there's a problem — currently, when you click the video it starts to play, but it causes the <code><div></code> to also be hidden at the same time. This is because the video is inside the <code><div></code> — it is part of it — so clicking on the video actually runs <em>both</em> the above event handlers.</p>
<h4 id="Bubbling_and_capturing_explained">Bubbling and capturing explained</h4>
<p>When an event is fired on an element that has parent elements (e.g. the {{htmlelement("video")}} in our case), modern browsers run two different phases — the <strong>capturing</strong> phase and the <strong>bubbling</strong> phase.</p>
<p>In the <strong>capturing</strong> phase:</p>
<ul>
<li>The browser checks to see if the element's outer-most ancestor ({{htmlelement("html")}}) has an <code>onclick</code> event handler registered on it in the capturing phase, and runs it if so.</li>
<li>Then it moves on to the next element inside <code><html></code> and does the same thing, then the next one, and so on until it reaches the element that was actually clicked on.</li>
</ul>
<p>In the <strong>bubbling</strong> phase, the exact opposite occurs:</p>
<ul>
<li>The browser checks to see if the element that was actually clicked on has an <code>onclick</code> event handler registered on it in the bubbling phase, and runs it if so.</li>
<li>Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the <code><html></code> element.</li>
</ul>
<p><a href="https://mdn.mozillademos.org/files/14075/bubbling-capturing.png"><img alt="" src="https://mdn.mozillademos.org/files/14075/bubbling-capturing.png" style="display: block; height: 452px; margin: 0px auto; width: 960px;"></a></p>
<p>(Click on image for bigger diagram)</p>
<p>In modern browsers, by default, all event handlers are registered in the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <code><video></code> element outwards to the <code><html></code> element. Along the way:</p>
<ul>
<li>It finds the <code>video.onclick...</code> handler and runs it, so the video first starts playing.</li>
<li>It then finds the <code>videoBox.onclick...</code> handler and runs it, so the video is hidden as well.</li>
</ul>
<h4 id="Fixing_the_problem_with_stopPropagation">Fixing the problem with stopPropagation()</h4>
<p>This is annoying behavior, but there is a way to fix it! The standard event object has a function available on it called <code><a href="/en-US/docs/Web/API/Event/stopPropagation">stopPropagation()</a></code>, which when invoked on a handler's event object makes it so that handler is run, but the event doesn't bubble any further up the chain, so no more handlers will be run.</p>
<p>We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:</p>
<pre class="brush: js notranslate">video.onclick = function(e) {
e.stopPropagation();
video.play();
};</pre>
<p>You can try making a local copy of the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/show-video-box.html">show-video-box.html source code</a> and having a go at fixing it yourself, or looking at the fixed result in <a href="http://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html">show-video-box-fixed.html</a> (also see the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/events/show-video-box-fixed.html">source code</a> here).</p>
<div class="note">
<p><strong>Note</strong>: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.</p>
</div>
<div class="note">
<p><strong>Note</strong>: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>, and setting the optional third property to <code>true</code>.</p>
</div>
<h4 id="Event_delegation">Event delegation</h4>
<p>Bubbling also allows us to take advantage of <strong>event delegation</strong> — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?</p>
<p>A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the <code>click</code> event listener on the parent <code><ul></code>, and events will bubble from the list items to the <code><ul></code>.</p>
<p>This concept is explained further on David Walsh's blog, with multiple examples — see <a href="https://davidwalsh.name/event-delegate">How JavaScript Event Delegation Works</a>.</p>
<h2 id="Conclusion">Conclusion</h2>
<p>You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.</p>
<p>Also, it is important to understand that the different contexts in which JavaScript is used tend to have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.</p>
<p>If there is anything you didn't understand, feel free to read through the article again, or <a href="/en-US/Learn#Contact_us">contact us</a> to ask for help.</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="http://www.quirksmode.org/js/events_order.html">Event order</a> (discussion of capturing and bubbling) — an excellently detailed piece by Peter-Paul Koch.</li>
<li><a href="http://www.quirksmode.org/js/events_access.html">Event accessing</a> (discussion of the event object) — another excellently detailed piece by Peter-Paul Koch.</li>
<li><a href="/en-US/docs/Web/Events">Event reference</a></li>
</ul>
<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}</p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
</ul>
|