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
Explain what is going to console.log, and in what order in this scenario if we click on Yahoo
**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**
26
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?**
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.
27
When **event.target** and **.this** are equal?
When we are at the second ( 2 ) phase, the target phase.
28
When working with taking (capturing or bubbling phase) the event listening, what is going to be the value of this?
This is going to refer to whatever element is currently being triggered during the capturing or bubbling phases.
29
When removing a listener, the 3rd parameter, the useCapture parameter, must have a value of?
***false***
30
What is the name of the 3rd parameter, when calling ***addEventListener*** or ***removeEventListener***
***useCapture***
31
The event object, contains what?
information about an event
32
The event object must be passed to functions, how?
must be passed to functions attached with event listeners * el.addEventListener( 'click', **theFn**, false );* * function theFn( **e** ) { }*
33
The event object, is often passed to functions like what parameter ( the name of the parameter)
like **e** theFn( **e** ) { }
34
In the event object, the available properties will depende on what factors?
on the type of **event,** that we are listening! if it´s a **click**, **load**, **mouseover** **event**, etc...
35
All browsers display the same properties on the event object?
**No**, there are some cross browser differences
36
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?
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
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?
YES
38
When the handler is assigned using an HTML-attribute, what is happening in the browser?
The browser read is, creates a new function from the attribute content and writes it to the DOM property. ## Footnote **The handler is always in the DOM property: the HTML-attribute is just one of the ways to initialize it**
39
Why doing this will give us an error? ## Footnote ***button.onclick = sayThanks();***
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
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?
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
Can we use **setAttribbute** for handlers? ## Footnote ***document.body.setAttribute( 'onclick', function() { alert(1) } );***
No, it won´t work. a click on will generate errors, because attributes are always strings, function becomes a string
42
Why this approach of assigning event handlers will not work as expected? ## Footnote ***input.onclick = function() { alert( 1 ); }*** ***input.onclick = function() { alert( 2 ); }***
The last code, will replace the first one. A new **DOM property** will override the existing one
43
When we add an **event handler** via **addEventListener**, and **we are not** storing the function **into a variable**, what could happend later?
We can´t remove it. There´s **no way to "read back" handlers** assigned by **addEventListener**
44
When an **event happens**, the **browser** what **creates**?
It creates an **event object**, puts details into it and **passes it as an argument** to the **handler**.
45
Name the 3 ways to assign event handlers, and how they do it?
1 - HTML attribute: ***​onclick = " ... ";*** 2 - DOM property***: elem.onclick = function*** 3 - Methods: ***elem.addEventListener( event, handler[, phase] )***
46
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
**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
**focus event** do bubble?
**NO, it´s an exception, rather than a rule**, most events do bubble!
48
How a parent element can get the details about where an event actually happend?
Taking advantage of the bubble phase
49
the event.target is?
Is the target element that initiated the event, it doesn´t change through the bubbling phase
50
A bubbling event goes from where to where?
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
It's normally to stop bubbling without a need? and why?
NO, bubbling it is convenient. Sometimes event.stopPropagation() creates hidden pitfalls that later may become problems
52
What kind of handlers don´t know anything about the capturing phase?
Handlers added using: **on property** or using **HTML attributtes**, also **addEventListener(event, handler)**
53
Bubbling and capturing lay the fundation of what pattern?
the event delegation pattern
54
Why we need to use **addEventListener** when assigning **event handlers** to the **document object**, and not handle them with for example **document.onclick**?
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
For what it's used the event delegation pattern? and describe the algorithm
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
Describe the benefits of the event delegation algorithm?
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
What are the limitations of the event delegation pattern?
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
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"
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
Many events automatically lead to browser actions... Give some examples
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
How can we prevent the default browser actions
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
Certain events flow one into another, if we prevent the first event, there will be no second... give an example with mousedown
mousedown on an field leads to focusing in it, and the focus event. If we prevent the mousedown event, there´s no focus.
62
What are the possible values of the property on event: event.defaultPrevented
The property event.defaultPrevented is **true** if the default action was prevented, and **false** otherwise.
63
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
YES
64
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 telling what happens with the menu: ***open (menu open), select (an item is selected)*** and so on
65
Events form a hierarchy? just like?
DOM element classes
66
In the event hierarchy, who is the root?
the root is the built-in Event class
67
How can we create an event object, and describe it?
***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
***var event = new Event( event type[, options] );*** What is this?
A new Event object
69
***var event = new Event( event type[, options] );*** This is a new event object, what is ***event type***?
***event type:*** may be any string, like ***'click'*** or own like '***hey-ho!'***
70
***var event = new Event( event type[, options] );*** This is a new event object, what is ***options***?
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
After an event object is created, how can we "run" it on an element ?
using the call ***elem.dispatchEvent( event )***
72
When using ***Custom Events*** can we use ***on***, like ***document.onhello***?
No, because ***on*** only exists for built-in events, we should use ***addEventListener***
73
It's say that technically ***CustomEvent*** is the same as ***Event***, with one exception ?
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
For ***Custom UI Events***, we should use the ***Event constructor,*** or other ***constructor/s***? Give an example
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
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?
Like ***CustomEvent*** has the ***detail property***, and that property can hold any data, we can evade conflicts with other event properties
76
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)
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
What means that events are processed asyncrhonously?
If the browser is processing ***onclick*** and in the process a new event occurs, then it awaits till ***onclick*** processing is finished.
78
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."
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
What advantages gives the native events constructors like ## Footnote ***MouseEvent, KeyboardEvent, etc...***
They accept properties specific to that event type, ex: ***clientX*** for mouse events
80
For custom events, what we shoud use? what is the plus of using it?
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
We **should** or **should NOT**, generate browser events as a hacky way to run handlers?
We **should NOT** generate. It's bad architecture most of the time
82
Describe what is happening in the picture
there’s a **hide() function**. It generates the "**hide**" **event** 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
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...
**Si, los elementos padres tienen que estar escuchando por el mismo tipo de evento**
84
Explain what is going to **console.log, and in what order** in this scenario if we click on **Yahoo**
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
Explain what is going to **console.log, and in what order** in this scenario if we **click on Yahoo**
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
Explain what is going to **console.log**, and in what order in this scenario if we **click on Yahoo**
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
Explain what is going to console.log, and in what order in this scenario if we click on Yahoo
**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
What is going to happen on this script
**Nothing!** because **dispatchEvent is commented**, we need it in order to run the event