Skip to content

Commit 8f85dae

Browse files
authored
Merge pull request #527 from j-llano/patch-1
Focusing: focus/blur
2 parents 6411cef + 64a0a3c commit 8f85dae

File tree

1 file changed

+74
-74
lines changed

1 file changed

+74
-74
lines changed
Lines changed: 74 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,62 @@
1-
# Focusing: focus/blur
1+
# Enfocado: enfoque/desenfoque
22

3-
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.
44

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.
66

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.
88

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.
1010

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.
1212

13-
## Events focus/blur
13+
## Eventos focus/blur
1414

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.
1616

17-
Let's use them for validation of an input field.
17+
Utilicémolos para la validación de un campo de entrada.
1818

19-
In the example below:
19+
En el ejemplo a continuación:
2020

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):
2323

2424
```html run autorun height=60
2525
<style>
2626
.invalid { border-color: red; }
2727
#error { color: red }
2828
</style>
2929

30-
Your email please: <input type="email" id="input">
30+
Su correo por favor: <input type="email" id="input">
3131

3232
<div id="error"></div>
3333

3434
<script>
3535
*!*input.onblur*/!* = function() {
3636
if (!input.value.includes('@')) { // not email
3737
input.classList.add('invalid');
38-
error.innerHTML = 'Please enter a correct email.'
38+
error.innerHTML = 'Por favor introduzca un correo válido.'
3939
}
4040
};
4141
4242
*!*input.onfocus*/!* = function() {
4343
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
4545
this.classList.remove('invalid');
4646
error.innerHTML = "";
4747
}
4848
};
4949
</script>
5050
```
5151

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.
5353

5454

55-
## Methods focus/blur
55+
## Métodos focus/blur
5656

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.
5858

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:
6060

6161
```html run autorun height=80
6262
<style>
@@ -65,16 +65,16 @@ For instance, let's make the visitor unable to leave the input if the value is i
6565
}
6666
</style>
6767

68-
Your email please: <input type="email" id="input">
69-
<input type="text" style="width:220px" placeholder="make email invalid and try to focus here">
68+
Su correo por favor: <input type="email" id="input">
69+
<input type="text" style="width:220px" placeholder="hacer que el correo sea inválido y tratar de enfocar aquí">
7070

7171
<script>
7272
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
7575
this.classList.add("error");
7676
*!*
77-
// ...and put the focus back
77+
// ...y volver a enfocar
7878
input.focus();
7979
*/!*
8080
} else {
@@ -84,59 +84,59 @@ Your email please: <input type="email" id="input">
8484
</script>
8585
```
8686

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)).
8888

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.
9090

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.
9292

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.
9595
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:
9797
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.
100100
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.
102102
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.
104104
```
105-
## Allow focusing on any element: tabindex
105+
## Permitir enfocado sobre cualquier elemento: tabindex
106106

107-
By default, many elements do not support focusing.
107+
Por defecto, muchos elementos no permiten enfoque.
108108

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.
110110

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.
112112

113-
This can be changed using HTML-attribute `tabindex`.
113+
Esto puede ser modificado usando el atributo HTML `tabindex`.
114114

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.
116116

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.
118118

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).
120120

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).
122122

123-
There are two special values:
123+
Existen dos valores especiales:
124124

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"`.
126126

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>.
128128

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.
130130

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`:
132132

133133
```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.
135135
<ul>
136-
<li tabindex="1">One</li>
137-
<li tabindex="0">Zero</li>
138-
<li tabindex="2">Two</li>
139-
<li tabindex="-1">Minus one</li>
136+
<li tabindex="1">Uno</li>
137+
<li tabindex="0">Cero</li>
138+
<li tabindex="2">Dos</li>
139+
<li tabindex="-1">Menos uno</li>
140140
</ul>
141141

142142
<style>
@@ -145,20 +145,20 @@ Click the first item and press Tab. Keep track of the order. Please note that ma
145145
</style>
146146
```
147147

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`.
149149

150-
```smart header="The property `elem.tabIndex` works too"
151-
We can add `tabindex` from JavaScript by using the `elem.tabIndex` property. That has the same effect.
150+
```smart header="La propiedad `elem.tabIndex` también funciona"
151+
Podemos añadir `tabindex` desde JavaScript utilizando la propiedad `elem.tabIndex`. Se consigue el mismo resultado.
152152
```
153153
154-
## Delegation: focusin/focusout
154+
## Delegación: focusin/focusout
155155
156-
Events `focus` and `blur` do not bubble.
156+
Los eventos `focus` y `blur` no se propagan.
157157
158-
For instance, we can't put `onfocus` on the `<form>` to highlight it, like this:
158+
Por ejemplo, no podemos añadir `onfocus` en <form> para resaltarlo, así:
159159
160160
```html autorun height=80
161-
<!-- on focusing in the form -- add the class -->
161+
<!-- enfocando en el formulario -- añadir la clase -->
162162
<form *!*onfocus="this.className='focused'"*/!*>
163163
<input type="text" name="name" value="Name">
164164
<input type="text" name="surname" value="Surname">
@@ -167,13 +167,13 @@ For instance, we can't put `onfocus` on the `<form>` to highlight it, like this:
167167
<style> .focused { outline: 1px solid red; } </style>
168168
```
169169

170-
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.
171171

172-
There are two solutions.
172+
Existen dos soluciones.
173173

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.
175175

176-
This will work:
176+
Esto funcionará:
177177

178178
```html autorun height=80
179179
<form id="form">
@@ -185,18 +185,18 @@ This will work:
185185

186186
<script>
187187
*!*
188-
// put the handler on capturing phase (last argument true)
188+
// pon el manejador en fase de captura (último argumento "verdadero")
189189
form.addEventListener("focus", () => form.classList.add('focused'), true);
190190
form.addEventListener("blur", () => form.classList.remove('focused'), true);
191191
*/!*
192192
</script>
193193
```
194194

195-
Second, there are `focusin` and `focusout` events -- exactly the same as `focus/blur`, but they bubble.
195+
Además, existen los eventos `focusin` and `focusout`: exactamente igual que `focus/blur` pero se propagan.
196196

197-
Note that they must be assigned using `elem.addEventListener`, not `on<event>`.
197+
Hay que tener en cuenta que han de asignarse utilizando `elem.addEventListener`, no `on<event>`.
198198

199-
So here's another working variant:
199+
Aquí hay otra opción que funciona:
200200

201201
```html autorun height=80
202202
<form id="form">
@@ -214,12 +214,12 @@ So here's another working variant:
214214
</script>
215215
```
216216

217-
## Summary
217+
## Resumen
218218

219-
Events `focus` and `blur` trigger on an element focusing/losing focus.
219+
Los eventos `focus` y `blur` hacen que un elemento se enfoque/pierda el foco.
220220

221-
Their specials are:
222-
- They do not bubble. Can use capturing state instead or `focusin/focusout`.
223-
- Most elements do not support focus by default. Use `tabindex` to make anything focusable.
221+
Se caracterizan por lo siguiente:
222+
- No se propagan. En su lugar se puede capturar el estado o usar `focusin/focusout`.
223+
- La mayoría de los elementos no permiten enfoque por defecto. Utliza `tabindex` para hacer cualquier elemento enfocable.
224224

225-
The current focused element is available as `document.activeElement`.
225+
El elemento enfocado actualmente se encuentra disponible en `document.activeElement`.

0 commit comments

Comments
 (0)