diff --git a/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md b/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md index 4d175ca01..e570bea4d 100644 --- a/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md +++ b/2-ui/2-events/04-default-browser-action/1-why-return-false-fails/solution.md @@ -1,16 +1,16 @@ -When the browser reads the `on*` attribute like `onclick`, it creates the handler from its content. +Cuando el navegador lee un atributo `on*` como `onclick`, crea el controlador a partir de su contenido. -For `onclick="handler()"` the function will be: +Para `onclick="handler()"` la función será: ```js function(event) { - handler() // the content of onclick + handler() // el contenido de onclick } ``` -Now we can see that the value returned by `handler()` is not used and does not affect the result. +Ahora podemos ver que el valor devuelto por `handler()` no se usa y no afecta el resultado. -The fix is simple: +La solución es simple: ```html run -the browser will go to w3.org +el navegador irá a w3.org ``` -The browser follows the URL on click, but we don't want it. +El navegador sigue la URL al hacer clic, pero no la queremos. -How to fix? +¿Como se arregla? diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md index 25079cb8d..bf3346ff8 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.md @@ -1,5 +1,5 @@ -That's a great use of the event delegation pattern. +Ese es un gran uso para el patrón de delegación de eventos. -In real life instead of asking we can send a "logging" request to the server that saves the information about where the visitor left. Or we can load the content and show it right in the page (if allowable). +En la vida real, en lugar de preguntar, podemos enviar una solicitud de "logging" al servidor que guarda la información sobre dónde se fue el visitante. O podemos cargar el contenido y mostrarlo directamente en la página (si está permitido). -All we need is to catch the `contents.onclick` and use `confirm` to ask the user. A good idea would be to use `link.getAttribute('href')` instead of `link.href` for the URL. See the solution for details. +Todo lo que necesitamos es capturar el `contents.onclick` y usar `confirm` para preguntar al usuario. Una buena idea sería usar `link.getAttribute('href')` en lugar de `link.href` para la URL. Consulte la solución para obtener más detalles. diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html index 51ac0838b..39b533722 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/solution.view/index.html @@ -16,7 +16,7 @@
#contents

- How about to read Wikipedia or visit W3.org and learn about modern standards? + ¿Que tal si leemos Wikipedia o visitamos W3.org y aprendemos sobre los estándares modernos?

@@ -24,7 +24,7 @@ contents.onclick = function(event) { function handleLink(href) { - let isLeaving = confirm(`Leave for ${href}?`); + let isLeaving = confirm(`¿Irse a ${href}?`); if (!isLeaving) return false; } diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html index f0c934391..110a62d1b 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/source.view/index.html @@ -16,7 +16,7 @@
#contents

- How about to read Wikipedia or visit W3.org and learn about modern standards? + ¿Que tal si leemos Wikipedia o visitamos W3.org y aprendemos sobre los estándares modernos?

diff --git a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md index 6ca456c2c..07e2482f1 100644 --- a/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md +++ b/2-ui/2-events/04-default-browser-action/2-catch-link-navigation/task.md @@ -2,15 +2,15 @@ importance: 5 --- -# Catch links in the element +# Captura enlaces en el elemento -Make all links inside the element with `id="contents"` ask the user if they really want to leave. And if they don't then don't follow. +Haz que todos los enlaces dentro del elemento con `id="contents"` pregunten al usuario si realmente quiere irse. Y si no quiere, no sigas. -Like this: +Así: [iframe height=100 border=1 src="solution"] -Details: +Detalles: -- HTML inside the element may be loaded or regenerated dynamically at any time, so we can't find all links and put handlers on them. Use event delegation. -- The content may have nested tags. Inside links too, like `...`. +- El HTML dentro del elemento puede cargarse o regenerarse dinámicamente en cualquier momento, por lo que no podemos encontrar todos los enlaces y ponerles controladores. Utilice la delegación de eventos. +- El contenido puede tener etiquetas anidadas. Dentro de los enlaces también, como `...`. diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md index 5ff60b5c0..407ad45e5 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.md @@ -1 +1 @@ -The solution is to assign the handler to the container and track clicks. If a click is on the `` link, then change `src` of `#largeImg` to the `href` of the thumbnail. +La solución es asignar el controlador al contenedor y realizar un seguimiento de los clics. Si haces clic en el enlace ``, cambias `src` de `#largeImg` por el `href` de la miniatura. diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html index 524bc7152..8d0616e1c 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/index.html @@ -9,24 +9,24 @@ -

Large image

+

Large image

diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html index c488ddcc2..83866900f 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/index.html @@ -9,24 +9,24 @@ -

Large image

+

Large image

diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md b/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md index f7571cc80..443a3f3f6 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/task.md @@ -2,12 +2,12 @@ importance: 5 --- -# Image gallery +# Galería de imágenes -Create an image gallery where the main image changes by the click on a thumbnail. +Crea una galería de imágenes donde la imagen principal cambia al hacer clic en una miniatura. -Like this: +Así: [iframe src="solution" height=600] -P.S. Use event delegation. +P.D. Utiliza la delegación de eventos. diff --git a/2-ui/2-events/04-default-browser-action/article.md b/2-ui/2-events/04-default-browser-action/article.md index ceac160c1..7eabeb12a 100644 --- a/2-ui/2-events/04-default-browser-action/article.md +++ b/2-ui/2-events/04-default-browser-action/article.md @@ -1,43 +1,43 @@ -# Browser default actions +# Acciones predeterminadas del navegador -Many events automatically lead to certain actions performed by the browser. +Muchos eventos conducen automáticamente a determinadas acciones realizadas por el navegador. -For instance: +Por ejemplo: -- A click on a link - initiates navigation to its URL. -- A click on a form submit button - initiates its submission to the server. -- Pressing a mouse button over a text and moving it - selects the text. +- Un clic en un enlace: inicia la navegación a su URL. +- Un clic en el botón de envío de un formulario inicia su envío al servidor. +- Al presionar un botón del ratón sobre un texto y moverlo, se selecciona el texto. -If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and want to implement another behavior instead. +Si manejamos un evento en JavaScript, es posible que no queramos que suceda la acción correspondiente del navegador e implementar en cambio otro comportamiento. -## Preventing browser actions +## Evitar las acciones del navegador -There are two ways to tell the browser we don't want it to act: +Hay dos formas de decirle al navegador que no queremos que actúe: -- The main way is to use the `event` object. There's a method `event.preventDefault()`. -- If the handler is assigned using `on` (not by `addEventListener`), then returning `false` also works the same. +- La forma principal es utilizar el objeto `event`. Hay un método `event.preventDefault()`. +- Si el controlador se asigna usando `on` (no por `addEventListener`), entonces devolver `false` también funciona igual. -In this HTML a click on a link doesn't lead to navigation, browser doesn't do anything: +En este HTML, un clic en un enlace no conduce a la navegación, el navegador no hace nada: ```html autorun height=60 no-beautify -Click here -or -here +Haz clic aquí +o +aquí ``` -In the next example we'll use this technique to create a JavaScript-powered menu. +En el siguiente ejemplo usaremos esta técnica para crear un menú basado en JavaScript. -```warn header="Returning `false` from a handler is an exception" -The value returned by an event handler is usually ignored. +```warn header="Regresar `false` desde un controlador es una excepción" +El valor devuelto por un controlador de eventos generalmente se ignora. -The only exception is `return false` from a handler assigned using `on`. +La única excepción es `return false` de un controlador asignado usando `on`. -In all other cases, `return` value is ignored. In particular, there's no sense in returning `true`. +En todos los demás casos, se ignora el valor `return`. En particular, no tiene sentido devolver `true`. ``` -### Example: the menu +### Ejemplo: el menú -Consider a site menu, like this: +Considere un menú de sitio, como este: ```html ``` -Here's how it looks with some CSS: +Así es como se ve con algo de CSS: [iframe height=70 src="menu" link edit] -Menu items are implemented as HTML-links ``, not buttons ` + - ``` -Now, in addition to that context menu we'd like to implement document-wide context menu. +Ahora, además de ese menú contextual, nos gustaría implementar un menú contextual para todo el documento. -Upon right click, the closest context menu should show up. +Al hacer clic derecho, debería aparecer el menú contextual más cercano. ```html autorun height=80 no-beautify run -

Right-click here for the document context menu

- +

Haz clic derecho aquí para el menú contextual del documento

+ ``` -The problem is that when we click on `elem`, we get two menus: the button-level and (the event bubbles up) the document-level menu. +El problema es que cuando hacemos clic en `elem`, obtenemos dos menús: el de nivel de botón y (el evento emerge) el menú de nivel de documento. -How to fix it? One of solutions is to think like: "When we handle right-click in the button handler, let's stop its bubbling" and use `event.stopPropagation()`: +¿Como arreglarlo? Una de las soluciones es pensar así: "Cuando hagamos clic con el botón derecho en el controlador de botones, detengamos su propagación" y usemos `event.stopPropagation()`: ```html autorun height=80 no-beautify run -

Right-click for the document menu

- +

Haz clic derecho para el menú del documento

+ ``` -Now the button-level menu works as intended. But the price is high. We forever deny access to information about right-clicks for any outer code, including counters that gather statistics and so on. That's quite unwise. +Ahora, el menú de nivel de botón funciona según lo previsto. Pero el precio es alto. Siempre negamos el acceso a la información sobre los clics con el botón derecho del ratón para cualquier código externo, incluidos los contadores que recopilan estadísticas, etc. Eso es bastante imprudente. -An alternative solution would be to check in the `document` handler if the default action was prevented? If it is so, then the event was handled, and we don't need to react on it. +¿Sería una solución alternativa verificar en el controlador `document` si se evitó la acción predeterminada? Si es así, entonces se manejó el evento y no necesitamos reaccionar ante él. ```html autorun height=80 no-beautify run -

Right-click for the document menu (added a check for event.defaultPrevented)

- +

Haz clic con el botón derecho en el menú del documento (se agregó una marca de verificación para event.defaultPrevented)

+ ``` -Now everything also works correctly. If we have nested elements, and each of them has a context menu of its own, that would also work. Just make sure to check for `event.defaultPrevented` in each `contextmenu` handler. +Ahora todo también funciona correctamente. Si tenemos elementos anidados, y cada uno de ellos tiene un menú contextual propio, eso también funcionaría. Solo asegúrate de buscar `event.defaultPrevented` en cada controlador de `contextmenu`. -```smart header="event.stopPropagation() and event.preventDefault()" -As we can clearly see, `event.stopPropagation()` and `event.preventDefault()` (also known as `return false`) are two different things. They are not related to each other. +```smart header="event.stopPropagation() y event.preventDefault()" +Como podemos ver claramente, `event.stopPropagation()` y `event.preventDefault()` (también conocido como `return false`) son dos cosas diferentes. No están relacionados entre sí. ``` -```smart header="Nested context menus architecture" -There are also alternative ways to implement nested context menus. One of them is to have a single global object with a handler for `document.oncontextmenu`, and also methods that allow us to store other handlers in it. +```smart header="Arquitectura de menús contextuales anidados" +También hay formas alternativas de implementar menús contextuales anidados. Uno de ellos es tener un único objeto global con un manejador para `document.oncontextmenu`, y también métodos que nos permitan almacenar otros manejadores en él. -The object will catch any right-click, look through stored handlers and run the appropriate one. +El objeto detectará cualquier clic derecho, examinará los controladores almacenados y ejecutará el apropiado. -But then each piece of code that wants a context menu should know about that object and use its help instead of the own `contextmenu` handler. +Pero entonces cada fragmento de código que quiera un menú contextual debe conocer ese objeto y usar su ayuda en lugar del propio controlador `contextmenu`. ``` -## Summary +## Resumen -There are many default browser actions: +Hay muchas acciones predeterminadas del navegador: -- `mousedown` -- starts the selection (move the mouse to select). -- `click` on `` -- checks/unchecks the `input`. -- `submit` -- clicking an `` or hitting `key:Enter` inside a form field causes this event to happen, and the browser submits the form after it. -- `keydown` -- pressing a key may lead to adding a character into a field, or other actions. -- `contextmenu` -- the event happens on a right-click, the action is to show the browser context menu. -- ...there are more... +- `mousedown` -- inicia la selección (mueva el ratón para seleccionar). +- `click` en `` -- marca/desmarca el `input`. +- `submit` -- dar clic en `` o presionar `key:Enter` dentro de un campo de formulario hace que suceda este evento y el navegador envía el formulario a continuación. +- `keydown` -- presionar una tecla puede llevar a agregar un carácter a un campo u otras acciones. +- `contextmenu` -- el evento ocurre con un clic derecho, la acción es mostrar el menú contextual del navegador. +- ...hay mas... -All the default actions can be prevented if we want to handle the event exclusively by JavaScript. +Todas las acciones predeterminadas se pueden evitar si queremos manejar el evento exclusivamente mediante JavaScript. -To prevent a default action -- use either `event.preventDefault()` or `return false`. The second method works only for handlers assigned with `on`. +Para evitar una acción predeterminada, utiliza `event.preventDefault()` o `return false`. El segundo método funciona solo para los controladores asignados con `on`. -The `passive: true` option of `addEventListener` tells the browser that the action is not going to be prevented. That's useful for some mobile events, like `touchstart` and `touchmove`, to tell the browser that it should not wait for all handlers to finish before scrolling. +La opción `passive: true` de `addEventListener` le dice al navegador que la acción no se evitará. Eso es útil para algunos eventos móviles, como `touchstart` y `touchmove`, para decirle al navegador que no debe esperar a que todos los controladores terminen antes de desplazarse. -If the default action was prevented, the value of `event.defaultPrevented` becomes `true`, otherwise it's `false`. +Si se evitó la acción predeterminada, el valor de `event.defaultPrevented` se convierte en `true`, de lo contrario, es `false`. -```warn header="Stay semantic, don't abuse" -Technically, by preventing default actions and adding JavaScript we can customize the behavior of any elements. For instance, we can make a link `
` work like a button, and a button `