You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
An element receives the focus when the user either clicks on it or uses the `key:Tab` key on the keyboard. There's also an `autofocus` HTML attribute that puts the focus onto an element by default when a page loads and other means of getting the focus.
3
+
Un elemento se enfoca cuando el usuario hace click sobre él o pulsa `key:Tab`en el teclado. Existe también un atributo `autofocus` HTML que enfoca sobre un elemento por defecto cuando una página carga y otros medios de conseguir el enfoque.
4
4
5
-
Focusing on an element generally means: "prepare to accept the data here", so that's the moment when we can run the code to initialize the required functionality.
5
+
Enfocarse sobre un elemento generalmente significa: "prepárate para aceptar estos datos", por lo que es el momento en el cual podemos correr el código para inicializar la funcionalidad requerida.
6
6
7
-
The moment of losing the focus ("blur") can be even more important. That's when a user clicks somewhere else or presses `key:Tab`to go to the next form field, or there are other means as well.
7
+
El momento de desenfoque ("blur") puede ser incluso más importante. Ocurre cuando un usuario clicka en otro punto o presiona `key:Tab`para ir al siguiente apartado, también hay otras maneras.
8
8
9
-
Losing the focus generally means: "the data has been entered", so we can run the code to check it or even to save it to the server and so on.
9
+
Perder el foco o desenfocarse generalmente significa: "los datos ya han sido introducidos", por lo que podemos correr el código para comprobarlo, para guardarlo en el servidor, etc.
10
10
11
-
There are important peculiarities when working with focus events. We'll do the best to cover them further on.
11
+
Existen importantes peculiaridades al trabajar con eventos de enfoque. Haremos lo posible para abarcarlas a continuación.
12
12
13
-
## Events focus/blur
13
+
## Eventos focus/blur
14
14
15
-
The `focus`event is called on focusing, and`blur`-- when the element loses the focus.
15
+
El evento `focus`es llamado al enfocar, y`blur`cuando el elemento pierde el foco.
16
16
17
-
Let's use them for validation of an input field.
17
+
Utilicémolos para la validación de un campo de entrada.
18
18
19
-
In the example below:
19
+
En el ejemplo a continuación:
20
20
21
-
-The `blur`handler checks if the field has an email entered, and if not -- shows an error.
22
-
-The `focus`handler hides the error message (on`blur`it will be checked again):
21
+
-El manejador `blur`comprueba si se ha introducido un correo, y en caso de que no muestra un error.
22
+
-El manejador `focus`esconde el mensaje de error (en`blur`se volverá a comprobar):
23
23
24
24
```html run autorun height=60
25
25
<style>
26
26
.invalid { border-color: red; }
27
27
#error { color: red }
28
28
</style>
29
29
30
-
Your email please: <inputtype="email"id="input">
30
+
Su correo por favor: <inputtype="email"id="input">
31
31
32
32
<divid="error"></div>
33
33
34
34
<script>
35
35
*!*input.onblur*/!*=function() {
36
36
if (!input.value.includes('@')) { // not email
37
37
input.classList.add('invalid');
38
-
error.innerHTML='Please enter a correct email.'
38
+
error.innerHTML='Por favor introduzca un correo válido.'
39
39
}
40
40
};
41
41
42
42
*!*input.onfocus*/!*=function() {
43
43
if (this.classList.contains('invalid')) {
44
-
//remove the "error" indication, because the user wants to re-enter something
44
+
//quitar la indicación "error", porque el usuario quiere reintroducir algo
45
45
this.classList.remove('invalid');
46
46
error.innerHTML="";
47
47
}
48
48
};
49
49
</script>
50
50
```
51
51
52
-
Modern HTML allows us to do many validations using input attributes: `required`, `pattern` and so on. And sometimes they are just what we need. JavaScript can be used when we want more flexibility. Also we could automatically send the changed value to the server if it's correct.
52
+
El HTML actual nos permite efectuar diversas validaciones utilizando atributos de entrada: `required`, `pattern`, etc. Y muchas veces son todo lo que necesitamos. JavaScript puede ser utilizado cuando queremos más flexibilidad. También podríamos enviar automáticamente el valor modificado al servidor si es correcto.
53
53
54
54
55
-
## Methods focus/blur
55
+
## Métodos focus/blur
56
56
57
-
Methods `elem.focus()`and`elem.blur()`set/unset the focus on the element.
57
+
Los métodos `elem.focus()`y`elem.blur()`fijan/eliminan el foco sobre el elemento.
58
58
59
-
For instance, let's make the visitor unable to leave the input if the value is invalid:
59
+
Por ejemplo, impidamos al visitante que deje la entrada si el valor es inválido:
60
60
61
61
```html run autorun height=80
62
62
<style>
@@ -65,16 +65,16 @@ For instance, let's make the visitor unable to leave the input if the value is i
65
65
}
66
66
</style>
67
67
68
-
Your email please: <inputtype="email"id="input">
69
-
<inputtype="text"style="width:220px"placeholder="make email invalid and try to focus here">
68
+
Su correo por favor: <inputtype="email"id="input">
69
+
<inputtype="text"style="width:220px"placeholder="hacer que el correo sea inválido y tratar de enfocar aquí">
70
70
71
71
<script>
72
72
input.onblur=function() {
73
-
if (!this.value.includes('@')) { //not email
74
-
//show the error
73
+
if (!this.value.includes('@')) { //no es un correo
74
+
//mostrar error
75
75
this.classList.add("error");
76
76
*!*
77
-
// ...and put the focus back
77
+
// ...y volver a enfocar
78
78
input.focus();
79
79
*/!*
80
80
} else {
@@ -84,59 +84,59 @@ Your email please: <input type="email" id="input">
84
84
</script>
85
85
```
86
86
87
-
It works in all browsers except Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=53579)).
87
+
Funciona en todos los navegadores excepto Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=53579)).
88
88
89
-
If we enter something into the input and then try to use `key:Tab`or click away from the `<input>`, then`onblur`returns the focus back.
89
+
Si introducimos algo en la entrada y luego intentamos pulsar `key:Tab`o hacer click fuera del `<input>`, entonces`onblur`vuelve a enfocar.
90
90
91
-
Please note that we can't "prevent losing focus" by calling`event.preventDefault()`in`onblur`, because`onblur`works *after* the element lost the focus.
91
+
Por favor tened en cuenta que no podemos "prevenir perder el foco" llamando a`event.preventDefault()`en`onblur`, porque`onblur`funciona *después* de que el elemento haya perdido el foco.
92
92
93
-
```warn header="JavaScript-initiated focus loss"
94
-
A focus loss can occur for many reasons.
93
+
```warn header="Pérdida de foco iniciada por JavaScript"
94
+
Una pérdida de foco puede ocurrir por diversas razones.
95
95
96
-
One of them is when the visitor clicks somewhere else. But also JavaScript itself may cause it, for instance:
96
+
Una de ellas ocurre cuando el visitante clicka en algún otro lado. Pero el propio JavaScript podría causarlo, por ejemplo:
97
97
98
-
- An `alert` moves focus to itself, so it causes the focus loss at the element (`blur` event), and when the `alert` is dismissed, the focus comes back (`focus` event).
99
-
- If an element is removed from DOM, then it also causes the focus loss. If it is reinserted later, then the focus doesn't return.
98
+
- Un `alert` traslada el foco hacia sí mismo, por lo que causa la pérdida de foco sobre el elemento (evento `blur`), y cuando `alert` es desestimado el foco vuelve (evento `focus`).
99
+
- Si un elemento es eliminado de DOM, también causa pérdida de foco. Si es reinsertado el foco no vuelve.
100
100
101
-
These features sometimes cause `focus/blur` handlers to misbehave -- to trigger when they are not needed.
101
+
Estas situaciones a veces causan que los manejadores `focus/blur` no funcionen adecuadamente y se activen cuando no son necesarios.
102
102
103
-
The best recipe is to be careful when using these events. If we want to track user-initiated focus-loss, then we should avoid causing it ourselves.
103
+
Es recomendable tener cuidado al utilizar estos eventos. Si queremos rastrear pérdidas de foco iniciadas por el usuario deberíamos evitar causarlas nosotros mismos.
104
104
```
105
-
## Allow focusing on any element: tabindex
105
+
## Permitir enfocado sobre cualquier elemento: tabindex
106
106
107
-
By default, many elements do not support focusing.
107
+
Por defecto, muchos elementos no permiten enfoque.
108
108
109
-
The list varies a bit between browsers, but one thing is always correct: `focus/blur`support is guaranteed for elements that a visitor can interact with: `<button>`, `<input>`, `<select>`, `<a>` and so on.
109
+
La lista varía un poco entre navegadores, pero una cosa es siempre cierta: `focus/blur`está garantizado para elementos con los que el visitante puede interactuar: `<button>`, `<input>`, `<select>`, `<a>`, etc.
110
110
111
-
On the other hand, elements that exist to format something, such as`<div>`, `<span>`, `<table>` -- are unfocusable by default. The method`elem.focus()`doesn't work on them, and `focus/blur`events are never triggered.
111
+
En cambio, elementos que existen para formatear algo, tales como`<div>`, `<span>`, `<table>`, por defecto no son posibles de enfocar. El método`elem.focus()`no funciona en ellos, y los eventos `focus/blur`no son desencadenados.
112
112
113
-
This can be changed using HTML-attribute`tabindex`.
113
+
Esto puede ser modificado usando el atributo HTML `tabindex`.
114
114
115
-
Any element becomes focusable if it has`tabindex`. The value of the attribute is the order number of the element when `key:Tab` (or something like that) is used to switch between them.
115
+
Cualquier elemento se vuelve enfocable si contiene`tabindex`. El valor del atributo es el orden del elemento cuando `key:Tab` (o algo similar) es utilizado para cambiar entre ellos.
116
116
117
-
That is: if we have two elements, the first has`tabindex="1"`, and the second has`tabindex="2"`, then pressing`key:Tab`while in the first element -- moves the focus into the second one.
117
+
Es decir: si tenemos dos elementos, el primero contiene`tabindex="1"` y el segundo contiene`tabindex="2"`, al presionar`key:Tab`estando situado sobre el primer elemento se traslada el foco al segundo.
118
118
119
-
The switch order is: elements with `tabindex`from `1` and above go first (in the `tabindex` order), and then elements without `tabindex` (e.g. a regular `<input>`).
119
+
El orden de cambio es el siguiente: los elementos con `tabindex`desde "1" en adelante tienen prioridad (en el orden `tabindex`) y después los elementos sin `tabindex` (por ejemplo un <input> estándar).
120
120
121
-
Elements without matching`tabindex`are switched in the document source order (the default order).
121
+
Elementos sin el`tabindex`correspondiente van cambiando en el orden del código fuente del documento (el orden por defecto).
122
122
123
-
There are two special values:
123
+
Existen dos valores especiales:
124
124
125
-
-`tabindex="0"`puts an element among those without `tabindex`. That is, when we switch elements, elements with`tabindex=0` go after elements with `tabindex ≥ 1`.
125
+
-`tabindex="0"`incluye al elemento entre los que carecen `tabindex`. Esto es, cuando cambiamos entre elementos, elementos con`tabindex="0"` van después de elementos con `tabindex>="1"`.
126
126
127
-
Usually it's used to make an element focusable, but keep the default switching order. To make an element a part of the form on par with `<input>`.
127
+
Habitualmente se utiliza para hacer que un elemento sea enfocable y a la vez mantener el orden de cambio por defecto intacto. Para hacer que un elemento sea parte del formulario a la par con <input>.
128
128
129
-
-`tabindex="-1"`allows only programmatic focusing on an element. The `key:Tab`key ignores such elements, but method`elem.focus()`works.
129
+
-`tabindex="-1"`permite sólo enfoque programático sobre un elemento. `key:Tab`ignora esos elementos pero el método`elem.focus()`funciona.
130
130
131
-
For instance, here's a list. Click the first item and press`key:Tab`:
131
+
Por ejemplo, he aquí una lista. Clique sobre el primer ítem y pulse`key:Tab`:
132
132
133
133
```html autorun no-beautify
134
-
Click the first item and press Tab. Keep track of the order. Please note that many subsequent Tabs can move the focus out of the iframe in the example.
134
+
Clique sobre el primer ítem y pulse `key:Tab`. Fíjese en el orden. Por favor, tenga en cuenta que subsiguientes tabulados pueden desplazar el foco fuera del iframe en el ejemplo.
135
135
<ul>
136
-
<litabindex="1">One</li>
137
-
<litabindex="0">Zero</li>
138
-
<litabindex="2">Two</li>
139
-
<litabindex="-1">Minus one</li>
136
+
<litabindex="1">Uno</li>
137
+
<litabindex="0">Cero</li>
138
+
<litabindex="2">Dos</li>
139
+
<litabindex="-1">Menos uno</li>
140
140
</ul>
141
141
142
142
<style>
@@ -145,20 +145,20 @@ Click the first item and press Tab. Keep track of the order. Please note that ma
145
145
</style>
146
146
```
147
147
148
-
The order is like this: `1 - 2 - 0`. Normally, `<li>`does not support focusing, but `tabindex`full enables it, along with events and styling with`:focus`.
148
+
El orden es el siguiente: `1 - 2 - 0`. Normalmente, `<li>`no admite enfocado pero `tabindex`lo habilita, junto con eventos y estilado con`:focus`.
The example above doesn't work, because when user focuses on an `<input>`, the `focus` event triggers on that input only. It doesn't bubble up. So `form.onfocus`never triggers.
170
+
El ejemplo anterior no funciona porque cuando el usuario enfoca sobre un <input> el evento ´focus´ se inicia solamente sobre esa entrada, no se propaga, por lo que `form.onfocus`nunca se inicia.
171
171
172
-
There are two solutions.
172
+
Existen dos soluciones.
173
173
174
-
First, there's a funny historical feature: `focus/blur`do not bubble up, but propagate down on the capturing phase.
174
+
Para empezar, hay una característica histórica graciosa: `focus/blur`no se propagan hacia arriba, lo hacen hacia abajo en la fase de captura.
175
175
176
-
This will work:
176
+
Esto funcionará:
177
177
178
178
```html autorun height=80
179
179
<formid="form">
@@ -185,18 +185,18 @@ This will work:
185
185
186
186
<script>
187
187
*!*
188
-
//put the handler on capturing phase (last argument true)
188
+
//pon el manejador en fase de captura (último argumento "verdadero")
0 commit comments