diff --git a/2-ui/4-forms-controls/2-focus-blur/article.md b/2-ui/4-forms-controls/2-focus-blur/article.md index b866a5e2b..1b4a0d605 100644 --- a/2-ui/4-forms-controls/2-focus-blur/article.md +++ b/2-ui/4-forms-controls/2-focus-blur/article.md @@ -1,25 +1,25 @@ -# Focusing: focus/blur +# Enfocado: enfoque/desenfoque -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. +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. -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. +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. -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. +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. -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. +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. -There are important peculiarities when working with focus events. We'll do the best to cover them further on. +Existen importantes peculiaridades al trabajar con eventos de enfoque. Haremos lo posible para abarcarlas a continuación. -## Events focus/blur +## Eventos focus/blur -The `focus` event is called on focusing, and `blur` -- when the element loses the focus. +El evento `focus` es llamado al enfocar, y `blur` cuando el elemento pierde el foco. -Let's use them for validation of an input field. +Utilicémolos para la validación de un campo de entrada. -In the example below: +En el ejemplo a continuación: -- The `blur` handler checks if the field has an email entered, and if not -- shows an error. -- The `focus` handler hides the error message (on `blur` it will be checked again): +- El manejador `blur` comprueba si se ha introducido un correo, y en caso de que no muestra un error. +- El manejador `focus` esconde el mensaje de error (en `blur` se volverá a comprobar): ```html run autorun height=60 -Your email please: +Su correo por favor:
@@ -35,13 +35,13 @@ Your email please: *!*input.onblur*/!* = function() { if (!input.value.includes('@')) { // not email input.classList.add('invalid'); - error.innerHTML = 'Please enter a correct email.' + error.innerHTML = 'Por favor introduzca un correo válido.' } }; *!*input.onfocus*/!* = function() { if (this.classList.contains('invalid')) { - // remove the "error" indication, because the user wants to re-enter something + // quitar la indicación "error", porque el usuario quiere reintroducir algo this.classList.remove('invalid'); error.innerHTML = ""; } @@ -49,14 +49,14 @@ Your email please: ``` -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. +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. -## Methods focus/blur +## Métodos focus/blur -Methods `elem.focus()` and `elem.blur()` set/unset the focus on the element. +Los métodos `elem.focus()` y `elem.blur()` fijan/eliminan el foco sobre el elemento. -For instance, let's make the visitor unable to leave the input if the value is invalid: +Por ejemplo, impidamos al visitante que deje la entrada si el valor es inválido: ```html run autorun height=80 -Your email please: - +Su correo por favor: + ``` -It works in all browsers except Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=53579)). +Funciona en todos los navegadores excepto Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=53579)). -If we enter something into the input and then try to use `key:Tab` or click away from the ``, then `onblur` returns the focus back. +Si introducimos algo en la entrada y luego intentamos pulsar `key:Tab` o hacer click fuera del ``, entonces `onblur` vuelve a enfocar. -Please note that we can't "prevent losing focus" by calling `event.preventDefault()` in `onblur`, because `onblur` works *after* the element lost the focus. +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. -```warn header="JavaScript-initiated focus loss" -A focus loss can occur for many reasons. +```warn header="Pérdida de foco iniciada por JavaScript" +Una pérdida de foco puede ocurrir por diversas razones. -One of them is when the visitor clicks somewhere else. But also JavaScript itself may cause it, for instance: +Una de ellas ocurre cuando el visitante clicka en algún otro lado. Pero el propio JavaScript podría causarlo, por ejemplo: -- 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). -- 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. +- 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`). +- Si un elemento es eliminado de DOM, también causa pérdida de foco. Si es reinsertado el foco no vuelve. -These features sometimes cause `focus/blur` handlers to misbehave -- to trigger when they are not needed. +Estas situaciones a veces causan que los manejadores `focus/blur` no funcionen adecuadamente y se activen cuando no son necesarios. -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. +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. ``` -## Allow focusing on any element: tabindex +## Permitir enfocado sobre cualquier elemento: tabindex -By default, many elements do not support focusing. +Por defecto, muchos elementos no permiten enfoque. -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: `