Skip to content

Events: change, input, cut, copy, paste #333

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
128d0eb
Traslation
nahuelcoder Aug 4, 2020
d369922
Update 2-ui/4-forms-controls/3-events-change-input/1-deposit-calculat…
nahuelcoder Aug 4, 2020
9bbbc84
Update 2-ui/4-forms-controls/3-events-change-input/1-deposit-calculat…
nahuelcoder Aug 4, 2020
8831b79
Update 2-ui/4-forms-controls/3-events-change-input/1-deposit-calculat…
nahuelcoder Aug 4, 2020
8a2add4
Update 2-ui/4-forms-controls/3-events-change-input/1-deposit-calculat…
nahuelcoder Aug 4, 2020
bef1f0b
Update article.md
nahuelcoder Aug 4, 2020
b468075
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 4, 2020
9cb4d94
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 4, 2020
67a6dec
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 4, 2020
a7167a3
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 4, 2020
91ecc00
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 4, 2020
8bd040e
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
fc9a2de
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
729fc97
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
9a0f19f
Update article.md
nahuelcoder Aug 5, 2020
433eff8
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
10bd620
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
c5f2ec2
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
3dac9e0
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
0b8adf2
Update 2-ui/4-forms-controls/3-events-change-input/article.md
nahuelcoder Aug 5, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,33 @@

<body>

Deposit calculator.
Calculadora de depósito.

<form name="calculator">
<table>
<tr>
<td>Initial deposit</td>
<td>Depósito inicial</td>
<td>
<input name="money" type="number" value="10000" required>
</td>
</tr>
<tr>
<td>How many months?</td>
<td>¿Cuántos meses?</td>
<td>
<select name="months">
<option value="3">3 (minimum)</option>
<option value="6">6 (half-year)</option>
<option value="12" selected>12 (one year)</option>
<option value="18">18 (1.5 years)</option>
<option value="24">24 (2 years)</option>
<option value="30">30 (2.5 years)</option>
<option value="36">36 (3 years)</option>
<option value="60">60 (5 years)</option>
<option value="3">3 (mínimo)</option>
<option value="6">6 (medio año)</option>
<option value="12" selected>12 (un año)</option>
<option value="18">18 (1.5 años)</option>
<option value="24">24 (2 años)</option>
<option value="30">30 (2.5 años)</option>
<option value="36">36 (3 años)</option>
<option value="60">60 (5 años)</option>
</select>
</td>
</tr>
<tr>
<td>Interest per year?</td>
<td>¿Interés anual?</td>
<td>
<input name="interest" type="number" value="5" required>
</td>
Expand All @@ -62,8 +62,8 @@

<table id="diagram">
<tr>
<th>Was:</th>
<th>Becomes:</th>
<th>Inicial:</th>
<th>Final:</th>
</tr>
<tr>
<th id="money-before"></th>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,33 @@

<body>

Deposit calculator.
Calculadora de depósito.

<form name="calculator">
<table>
<tr>
<td>Initial deposit</td>
<td>Depósito inicial</td>
<td>
<input name="money" type="number" value="10000" required>
</td>
</tr>
<tr>
<td>How many months?</td>
<td>¿Cuántos meses?</td>
<td>
<select name="months">
<option value="3">3 (minimum)</option>
<option value="6">6 (half-year)</option>
<option value="12" selected>12 (one year)</option>
<option value="18">18 (1.5 years)</option>
<option value="24">24 (2 years)</option>
<option value="30">30 (2.5 years)</option>
<option value="36">36 (3 years)</option>
<option value="60">60 (5 years)</option>
<option value="3">3 (mínimo)</option>
<option value="6">6 (medio año)</option>
<option value="12" selected>12 (un año)</option>
<option value="18">18 (1.5 años)</option>
<option value="24">24 (2 años)</option>
<option value="30">30 (2.5 años)</option>
<option value="36">36 (3 años)</option>
<option value="60">60 (5 años)</option>
</select>
</td>
</tr>
<tr>
<td>Interest per year?</td>
<td>¿Interés anual?</td>
<td>
<input name="interest" type="number" value="5" required>
</td>
Expand All @@ -62,8 +62,8 @@

<table id="diagram">
<tr>
<th>Was:</th>
<th>Becomes:</th>
<th>Inicial:</th>
<th>Final:</th>
</tr>
<tr>
<th id="money-before"></th>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ importance: 5

---

# Deposit calculator
# Calculadora de depósito

Create an interface that allows to enter a sum of bank deposit and percentage, then calculates how much it will be after given periods of time.
Crea una interfaz que permita ingresar una suma de depósito bancario y porcentaje, luego calcula cuánto será después de un periodo de tiempo determinado.

Here's the demo:
Acá una demostración:

[iframe src="solution" height="350" border="1"]

Any input change should be processed immediately.
Cualquier modificación debe ser procesada de inmediato.

The formula is:
La fórmula es:
```js
// initial: the initial money sum
// interest: e.g. 0.05 means 5% per year
// years: how many years to wait
// initial: la suma inicial de dinero
// interest: e.g. 0.05 significa 5% anual
// years: cuántos años esperar
let result = Math.round(initial * (1 + interest * years));
```
62 changes: 31 additions & 31 deletions 2-ui/4-forms-controls/3-events-change-input/article.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
# Events: change, input, cut, copy, paste
# Eventos: change, input, cut, copy, paste

Let's cover various events that accompany data updates.
Veamos varios eventos que acompañan la actualización de datos.

## Event: change
## Evento: change

The `change` event triggers when the element has finished changing.
El evento `change` se activa cuando el elemento finaliza un cambio.

For text inputs that means that the event occurs when it loses focus.
Para ingreso de texto significa que el evento ocurre cuando se pierde foco en el elemento.

For instance, while we are typing in the text field below -- there's no event. But when we move the focus somewhere else, for instance, click on a button -- there will be a `change` event:
Por ejemplo, mientras estamos escribiendo en el siguiente cuadro de texto -- no hay evento. Pero cuando movemos el focus (enfoque) a otro lado, por ejemplo hacemos click en un botón, entonces ocurre el evento `change`:

```html autorun height=40 run
<input type="text" onchange="alert(this.value)">
<input type="button" value="Button">
```

For other elements: `select`, `input type=checkbox/radio` it triggers right after the selection changes:
Para otros elementos: `select`, `input type=checkbox/radio` ocurre justo después de cambiar la opción seleccionada:

```html autorun height=40 run
<select onchange="alert(this.value)">
Expand All @@ -27,13 +27,13 @@ For other elements: `select`, `input type=checkbox/radio` it triggers right afte
```


## Event: input
## Evento: input

The `input` event triggers every time after a value is modified by the user.
El evento `input` ocurre cada vez que un valor es modificado por el ususario.

Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
A diferencia de los eventos de teclado, ocurre con el cambio a cualquier valor, incluso aquellos no que involucran acciones de teclado: copiar/pegar con el mouse o usar reconocimiento de voz para dictar texto.

For instance:
Por ejemplo:

```html autorun height=40 run
<input type="text" id="input"> oninput: <span id="result"></span>
Expand All @@ -44,25 +44,25 @@ For instance:
</script>
```

If we want to handle every modification of an `<input>` then this event is the best choice.
Si queremos manejar cualquier modificación en un `<input>` entonces este evento es la mejor opción.

On the other hand, `input` event doesn't trigger on keyboard input and other actions that do not involve value change, e.g. pressing arrow keys `key:⇦` `key:⇨` while in the input.
Por otro lado, el evento `input` no se activa con entradas del teclado u otras acciones que no involucren modificar un valor, e.g presionar las flechas de dirección `key:⇦` `key:⇨` mientras se está en el input.

```smart header="Can't prevent anything in `oninput`"
The `input` event occurs after the value is modified.
```smart header="No se puede evitar nada en `oninput`"
El evento `input` ocurre después de que el valor es modificado.

So we can't use `event.preventDefault()` there -- it's just too late, there would be no effect.
Por lo tanto no podemos usar `event.preventDefault()` para evitar modificaciones, en este caso ya es demasiado tarde por lo que no habría efecto.
```

## Events: cut, copy, paste
## Eventos: cut, copy, paste

These events occur on cutting/copying/pasting a value.
Estos eventos ocurren al cortar/copiar/pegar un valor.

They belong to [ClipboardEvent](https://www.w3.org/TR/clipboard-apis/#clipboard-event-interfaces) class and provide access to the data that is copied/pasted.
Estos pertenecen a la clase [ClipboardEvent](https://www.w3.org/TR/clipboard-apis/#clipboard-event-interfaces) y dan acceso a los datos copiados/pegados.

We also can use `event.preventDefault()` to abort the action, then nothing gets copied/pasted.
También podemos usar `event.preventDefault()` para cancelar la acción y que nada sea copiado/pegado.
Por ejemplo, el siguiente código evita tales eventos y muestra qué es los que estamos intentando cortar/copiar/pegar:

For instance, the code below prevents all such events and shows what we are trying to cut/copy/paste:

```html autorun height=40 run
<input type="text" id="input">
Expand All @@ -74,20 +74,20 @@ For instance, the code below prevents all such events and shows what we are tryi
</script>
```

Please note, that it's possible to copy/paste not just text, but everything. For instance, we can copy a file in the OS file manager, and paste it.
Por favor ten en cuenta que no solo es posible copiar/pegar texto, sino cualquier cosa. Por ejemplo, podemos copiar un archivo en el gestor de archivos del SO y pegarlo.

There's a list of methods [in the specification](https://www.w3.org/TR/clipboard-apis/#dfn-datatransfer) that can work with different data types including files, read/write to the clipboard.
Hay una lista de métodos [en la especificación](https://www.w3.org/TR/clipboard-apis/#dfn-datatransfer) que puede funcionar con diferentes tipos de datos incluyendo archivos, leer/escribir del portapapeles.

But please note that clipboard is a "global" OS-level thing. Most browsers allow read/write access to the clipboard only in the scope of certain user actions for the safety, e.g. in `onclick` event handlers.
Pero ten en cuenta que el portapapeles es algo a nivel "global" del SO. La mayoría de los navegadores dan acceso a leer/escribir del portapapeles dentro del alcance del usuario por cuestiones de seguridad, e.g. al manejar eventos `onclick`.

Also it's forbidden to generate "custom" clipboard events with `dispatchEvent` in all browsers except Firefox.
Además está prohibido generar eventos "personalizados" del portapapeles con `dispatchEvent` en todos los navegadores excepto Firefox.

## Summary
## Resumen

Data change events:
Eventos de modificación de datos:

| Event | Description | Specials |
| Evento | Descripción | Especiales |
|---------|----------|-------------|
| `change`| A value was changed. | For text inputs triggers on focus loss. |
| `input` | For text inputs on every change. | Triggers immediately unlike `change`. |
| `cut/copy/paste` | Cut/copy/paste actions. | The action can be prevented. The `event.clipboardData` property gives read/write access to the clipboard. |
| `change`| Un valor fue cambiado. | Para ingreso de texto, ocurre al perderse el enfoque |
| `input` | Para entrada de texto en cada cambio | Ocurre inmediatamente a diferencia de `change`. |
| `cut/copy/paste` | Acciones cortar/copiar/pegar | La acción puede ser cancelada. La propiedad `event.clipboardData` brinda acceso a leer/escribir del portapeles. |