1.4 - Events Flashcards

1
Q

Talking about Inline events, it is true to say that:

It´s best practice or bad practice?

A

Bad

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why inline events are bad practice, name a few reasons

A

Because:

Involve writing JS as HTML attribute values

Requires JS in HTML markup

They quickly become unmanageable and inefficient

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When talking about global envent handlers, we are saying that

involves assigning a function to a specific event of an element. Occurs in the JS and not in HTML

A

YES

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What involves a Global Event Handler

A

Assigning a function to a specific event of an element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why a global event handler, is prefered over an inline event

A

Because:

Occurs completely in JS

Techinically is a property of an element

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

There is 2 ways when we work with globan event handlers

Which are them?

A

one is referencing the function

the other one is assingning the funciton directly on the event

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

If we want to fire 2 click global events on the link, how can we do it?

For example:

a console.log

and an alert()

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the most common and preferred way to add listeners to a document?

A

Using event listeners

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why event listeners are the prefered way to work with events?

A

Because:

Does not use the “on” event naming convention

Can assign multiple functions per element

Can lookup Event listeners in Web Inspector

Can remove event listeners

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can we add an event listener?

A

with the method

element.addEventListener( ‘event’, theFunction, false )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

With event listeners can we lookup on them in the Web Inspector?

A

YES

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why we need to remove events?

A

Because the event listener is no longer needed

To prevent memory leaks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Why can we have a memory leak when working with events?

A

Example: if we remove an element that has some events attached to it, it may cause memory leaks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the method to remove an event?

A

element.removeEventListener( ‘event’, theFunction, false )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

el.addEventListener()

and

el.removeEventListener()

are methods of what?

A

methods of the DOM object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Whenever we have an event in JS, we have access to ?

A

The phases of that event

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can we retrieve the actual phase of an event?

A

with

event.eventPhase;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the event phases?

A

1 - Capturing phase

2 - Target Phase

3 - Bubbling Phase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Describe the image

Imagine clicking on the “Over the river, Charlie” text

A

Imagine we click on “over the River, Charlie”, in JS, in the DOM what´s happening although we don´t know that this is necessarilly going on behind the scenes but every element above the **is going to be notified during the capture phase so starting at the window level down to the document, the <html>, <body>, <table>, <tbody>, <tr>, and then finally the <td> will be notified that something beneath(debajo) has been clicked.

All this in red is part of the capture phase finally it gets to the target phase.

This explains why in the past we´ve seen event.target or e.target representing the element that was actually clicked or had the event occur. Phase 2º represent this target phase of the element that actually had the event occur.

Then, the 3º phase, the bubbling phase where every element above this(por arriba) in the DOM is again notified that this element(the clicked one) had an event occur to it so we see this 3º phase event propagation take place behind the scenes anytime we have an event on an element in the DOM.**

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

The Capture event phase

the number?

what is it?

how to invoke it¨?

A

number 1

where everything above(por arriba) the clicked element is notified, before(antes) the event.target takes place.

element.addEventListener( ‘click’, thFn, true )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The Bubbling event phase

the number?

what is it?

how to invoke it¨?

A

number 3

Where everything above(por arriba) is notified, after (después) the event.target has take place

element.addEventListener( ‘click’, theFn, false );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

To get notified and know where the capturing and bubbling phase is taking place, we need to do what?

A

We need to have one or more event listeners above in the DOM where the event.target is taking place.

That´s how happend that the capture and bubbling phase listen to them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can we stop the event?

A

invoking

event.stopPropagation();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

Todos los elementos estan escuchando por el evento ‘click’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

Document esta siendo escuchado en la fase de captura, por lo tanto va a ser el primer elemento que se va a tomar la captura del click

Yahoo va a escuchar el click y frenar la propagación e.stopPropagation()

Los otros elementos, estan escuchando en la fase de bubble, por lo tanto no van a escuchar el evento click, porque ya lo freno el elemento yahoo

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Tenemos un elemento hijo que esta escuchando por un evento ‘click’

Tenemos al elemento padre de este hijo, escuchando por un evento ‘click’

Lo que queremos hacer es capturar el evento en este padre(no importa en que fase, si captura o burbuja)

Tenemos que usar event.target?

A

No, we need to use the keyword .this when we are capturing the event on the parent´s elements

event.target: is the target element that initiated the event, it doesn´t change through the bubbling process

this: is the “current” element, the one that has a currently running handler on it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

When event.target and .this are equal?

A

When we are at the second ( 2 ) phase, the target phase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

When working with taking (capturing or bubbling phase) the event listening, what is going to be the value of this?

A

This is going to refer to whatever element is currently being triggered during the capturing or bubbling phases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

When removing a listener, the 3rd parameter, the useCapture parameter, must have a value of?

A

false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is the name of the 3rd parameter, when calling addEventListener or removeEventListener

A

useCapture

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

The event object, contains what?

A

information about an event

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

The event object must be passed to functions, how?

A

must be passed to functions attached with event listeners

  • el.addEventListener( ‘click’, theFn, false );*
  • function theFn( e ) { }*
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

The event object, is often passed to functions like what parameter ( the name of the parameter)

A

like e

theFn( e ) { }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

In the event object, the available properties will depende on what factors?

A

on the type of event, that we are listening!

if it´s a click, load, mouseover event, etc…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

All browsers display the same properties on the event object?

A

No, there are some cross browser differences

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

There’s a button in the variable. There are no handlers on it.

Which handlers run on click after the following code? Which alerts show up?

A

The answer: 1 and 2.

The first handler triggers, because it’s not removed by removeEventListener. To remove the handler we need to pass exactly the function that was assigned. And in the code a new function is passed, that looks the same, but is still another function.

To remove a function object, we need to store a reference to it, like this:

37
Q

It`s true that when we assing a handler event in an HTML-attribute, the browser will read it, creates a new function from the attribute content and writes it to the DOM property?

A

YES

38
Q

When the handler is assigned using an HTML-attribute, what is happening in the browser?

A

The browser read is, creates a new function from the attribute content and writes it to the DOM property.

The handler is always in the DOM property: the HTML-attribute is just one of the ways to initialize it

39
Q

Why doing this will give us an error?

button.onclick = sayThanks();

A

If we add brackets, then sayThanks() - will be the result of the function execution, so onclick in the last code becomes undefined (the function returns nothing).

40
Q

In the HTML markup, do we need the brackets like something as:

< a href=”#” onclick=”saythanks()” >

or

< a href=”#” onclick=”saythanks” >

Who is correct, and why?

A

We need to use the brackets!

< a href=”#” onclick=”saythanks()” >

When the browser reads the attribute, it creates a handler function with the body from its content.

So this example is the same as

button.onclick = function() {

sayThanks();

};

41
Q

Can we use setAttribbute for handlers?

document.body.setAttribute( ‘onclick’, function() { alert(1) } );

A

No, it won´t work.

a click on

will generate errors, because attributes are always strings, function becomes a string

42
Q

Why this approach of assigning event handlers will not work as expected?

input.onclick = function() { alert( 1 ); }

input.onclick = function() { alert( 2 ); }

A

The last code, will replace the first one.

A new DOM property will override the existing one

43
Q

When we add an event handler via addEventListener, and we are not storing the function into a variable, what could happend later?

A

We can´t remove it. There´s no way to “read back” handlers assigned by addEventListener

44
Q

When an event happens, the browser what creates?

A

It creates an event object, puts details into it and passes it as an argument to the handler.

45
Q

Name the 3 ways to assign event handlers, and how they do it?

A

1 - HTML attribute: ​onclick = “ … “;

2 - DOM property: elem.onclick = function

3 - Methods: elem.addEventListener( event, handler[, phase] )

46
Q

How can we define the bubbling phase?

Conceptually, when an event happens on an element..

and how can we take advantage of the bubble phase

A

When an event happens on an element, it first runs the handler on it, then on its parent, then all the way up on other ancestors.

To take advantage of the bubble phase, we need to listen for events on those other elements…

47
Q

focus event do bubble?

A

NO, it´s an exception, rather than a rule, most events do bubble!

48
Q

How a parent element can get the details about where an event actually happend?

A

Taking advantage of the bubble phase

49
Q

the event.target is?

A

Is the target element that initiated the event, it doesn´t change through the bubbling phase

50
Q

A bubbling event goes from where to where?

A

Goes from the target element staight up. Normally it goes upwards till , and then to document object, and some events even reach window object, calling all handlers on the path

51
Q

It’s normally to stop bubbling without a need? and why?

A

NO, bubbling it is convenient. Sometimes event.stopPropagation() creates hidden pitfalls that later may become problems

52
Q

What kind of handlers don´t know anything about the capturing phase?

A

Handlers added using:

on property or using HTML attributtes, also addEventListener(event, handler)

53
Q

Bubbling and capturing lay the fundation of what pattern?

A

the event delegation pattern

54
Q

Why we need to use addEventListener when assigning event handlers to the document object, and not handle them with for example document.onclick?

A

Because the latter will cause conflicts: new handlers overwrite old ones, and it´s normal that there are many handlers on document set by different parts of the code.

55
Q

For what it’s used the event delegation pattern?

and describe the algorithm

A

for adding same handling for many similar elements

1 - Put a single handler on the container

2 - In the handler - check the source element event.target

3 - If the event happened inside an element that interest us, then handle the event.

56
Q

Describe the benefits of the event delegation algorithm?

A

1 - Simplifies initialization and saves memory: no need to add many handlers

2 - Less code: when adding or removing elements, no need to add/remove handlers.

3 - DOM modifications: we can mass add/remove elements with innerHTML and alike

57
Q

What are the limitations of the event delegation pattern?

A

The event must be bubbling, some events do not bubble. Also, low-level handlers should not use event.stopPropagation()

The delegation may add CPUload, because the container-level handler reacts on events in any place of the container, no matter if they interest us or not

( Usually the load is negligible, so we don´t take it into account )

58
Q

Why in this case, it´s not useful to use event.stopPropagation()

1 - We create a nested menu. Each submenu handles clicks on its elements and calls stopPropagation so that outer parts don´t trigger.

2 - Later we decide to catch clicks inside the whole window, to track users behavior. Usually a counter code does that by document.addEventListener( ‘click’… )

3 - The counter won´t work over the area where clicks are stopped by stopPropagation. We´ve got a “dead zone”

A

El contador no va a funcionar en el menu porque al nosotros invocar event.stopPropagation, frenamos la propagación de la fase bubbling, y nunca va a llegar a ejecutarse el evento click en document (document.addEventListener…), osea el script de contador nunca va a poder contar los clicks dentro de esta zona, porque estamos frenando la propagación del evento de cada click, y nunca se va a llegar a ejecutar.

59
Q

Many events automatically lead to browser actions…

Give some examples

A

a click on a link - initiates going to tis url

a click on a submit button inside a form - initiate its submission to the server

60
Q

How can we prevent the default browser actions

A

There are 2 ways

1 - use the event object, there´s a method event.preventDefault()

2 - If the handler is assigned using on (not by addEventListener), then we can just return false from it

61
Q

Certain events flow one into another, if we prevent the first event, there will be no second…

give an example with mousedown

A

mousedown on an field leads to focusing in it, and the focus event. If we prevent the mousedown event, there´s no focus.

62
Q

What are the possible values of the property on event:

event.defaultPrevented

A

The property event.defaultPrevented

is true if the default action was prevented, and false otherwise.

63
Q

What it means that: Custom events can be used to create “graphical components”?

It means like for example: a root element of the menu may trigger events teling what happens with the menu: open (menu open), select (an item is selected) and so on

A

YES

64
Q

What it means that: Custom events can be used to create “graphical components”?

A

It means like for example: a root element of the menu may trigger events telling what happens with the menu: open (menu open), select (an item is selected) and so on

65
Q

Events form a hierarchy? just like?

A

DOM element classes

66
Q

In the event hierarchy, who is the root?

A

the root is the built-in Event class

67
Q

How can we create an event object, and describe it?

A

var event = new Event( event type[, options] );

event type: may be any string, like ‘click’ or our own like ‘hey-ho!’

options: The object with two optional properties

  • bubbles: true / false - If true, the event bubbles
  • cancelable: true / false - If true, then the “default action” may be prevented. Later we’ll see what it means for custom events.
68
Q

var event = new Event( event type[, options] );

What is this?

A

A new Event object

69
Q

var event = new Event( event type[, options] );

This is a new event object, what is event type?

A

event type: may be any string, like ‘click’ or own like ‘hey-ho!’

70
Q

var event = new Event( event type[, options] );

This is a new event object, what is options?

A

The object can have two optiona properties

bubbles: true / false - If true, then the event bubbles

cancelable: true / false - If true, then the “default action” may be prevented. Later we’ll see what it means for custom events

71
Q

After an event object is created, how can we “run” it on an element ?

A

using the call elem.dispatchEvent( event )

72
Q

When using Custom Events can we use on, like

document.onhello?

A

No, because on only exists for built-in events, we should use addEventListener

73
Q

It’s say that technically CustomEvent is the same as Event, with one exception ?

A

In the second argument (object) we can add an additional property detail for any custom information that we want to pass with the event.

74
Q

For Custom UI Events, we should use the Event constructor, or other constructor/s?

Give an example

A

We should use the right constructors for the kind of UI event that we want to handle:

A short list of classes for UI Events:

FocusEvent, MouseEvent, WheelEvent, KeyboardEvent

The right constructor allows to specify standard properties for that type of event.

75
Q

It is say that technically we could live without CustomEvent, as it’s similar as Event (we could assing any properties into a regular new Event object after its creation, simulating the detail property on CustomEvent), but with the exception of the detail property, what is the benefit?

A

Like CustomEvent has the detail property, and that property can hold any data, we can evade conflicts with other event properties

76
Q

What is the purpose of calling event.preventDefault() if the event has a non-standard name (knowing that it’s not know to the browser, and there’s no “default browser action” (like link)

A

The thing is that the event-generating code may plan some actions after dispatchEvent.

The call of event.preventDefault() is a way for the handler to send a signal that those actions shouldn’t be performed.

In that case the call to elem.dispatchEvent( event ) returns false, and the event-generating code knows that the processing shouldn´t continue.

Ejemplo:

Línea 24, puede retornar false, y la linea 15 va a ser false!

77
Q

What means that events are processed asyncrhonously?

A

If the browser is processing onclick and in the process a new event occurs, then it awaits till onclick processing is finished.

78
Q

What is the exception to this:

Asyncrhonously event processed:“If the browser is processing onclick and in the process a new event occurs, then it awaits till onclick processing is finished.”

A

The exception is when one event is initiated from within another one.

Then the control jumps to the nested event handler, and after it goes back..

In the example, the nested menu-open event is processed syncrhnously, during the onclick:

79
Q

What advantages gives the native events constructors like

MouseEvent, KeyboardEvent, etc…

A

They accept properties specific to that event type, ex: clientX for mouse events

80
Q

For custom events, what we shoud use? what is the plus of using it?

A

We should use CustomEvent constructor.

It has an additional option named detail, we should assign the event-specific data to it.

Then all handlers can access it as event.detail

81
Q

We should or should NOT, generate browser events as a hacky way to run handlers?

A

We should NOT generate. It’s bad architecture most of the time

82
Q

Describe what is happening in the picture

A

there’s a hide() function. It generates the “hideevent on the element #rabbit, notifying all interested parties that the rabbit is going to hide.

A handler set by rabbit.addEventListener(‘hide’,…) will learn about that and, if it wants, can prevent that action by calling event.preventDefault(). Then the rabbit won’t hide:

83
Q

Para hacer uso de la fase bubbling o capture, debemos estar escuchando en elementos padres, por el mismo tipo de evento? click, mouseover, keyup, etc…

A

Si, los elementos padres tienen que estar escuchando por el mismo tipo de evento

84
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

Todos los elementos estan escuchando en la fase de bubble (useCapture = false)

El elemento yahoo va a frenar la propagación con e.stopPropagation()

Por lo tanto lo único que se va a console.log es el elemento yahoo

85
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

El único elemento escuchando en la fase de captura (1) es el document

El resto de los elementos estan escuchando en la fase de bubble (2)

El elemento document esta frenando la propagación

Por lo tanto al hacer click en el elemento yahoo, solo vamos a consolear a document, ya que escucha el click en la fase de captura y frena la propagación del evento

86
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

Todos los elementos estan escuchando por clicks en la fase bubble ( 2 )

El elemento ul, esta frenando la propagacion del evento

Por lo tanto se va a consolear el click en yahoo, luego se va a capturar el click en el elemento ul, porque lo esta escuchando en la fase bubble, y ahí se frena la propagación

87
Q

Explain what is going to console.log, and in what order in this scenario if we click on Yahoo

A

Todos los elementos estan escuchando en la fase de bubble ( 2 )

El elemento ul, esta escuchando por el tipo de evento ‘keyup’ por lo tanto no importa para cuando hacemos click en yahoo

Lo que se va a consolear son los elementos:

yahoo

div

document

88
Q

What is going to happen on this script

A

Nothing! because dispatchEvent is commented, we need it in order to run the event