Skip to content

feat: Traduction de la page 'Introduction to browser events', + exercices & solutions #573

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -7,13 +7,13 @@

<body>

<input type="button" id="hider" value="Click to hide the text" />
<input type="button" id="hider" value="Cliquer pour cacher le texte" />

<div id="text">Text</div>
<div id="text">Texte</div>

<script>
// Here it doesn't matter how we hide the text,
// could also use style.display:
// Ici, pas d'imortance sur la façon de cacher le texte,
// on pourrait aussi utiliser style.display:
document.getElementById('hider').onclick = function() {
document.getElementById('text').hidden = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@

<body>

<input type="button" id="hider" value="Click to hide the text" />
<input type="button" id="hider" value="Cliquer pour cacher le texte" />

<div id="text">Text</div>
<div id="text">Texte</div>

<script>
/* your code */
/* votre code */
</script>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# Hide on click
# Cacher en cliquant

Add JavaScript to the `button` to make `<div id="text">` disappear when we click it.
Ajoutez du JavaScript au bouton `button` pour faire disparaître `<div id="text">` quand on clique dessus.

The demo:
La démo:

[iframe border=1 src="solution" height=80]
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Can use `this` in the handler to reference "the element itself" here:
Vous pouvez utiliser `this` dans le gestionnaire pour référencer "l'élément lui-même" :

```html run height=50
<input type="button" onclick="this.hidden=true" value="Click to hide">
<input type="button" onclick="this.hidden=true" value="Cliquer pour cacher">
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Hide self
# Se cacher soi-même

Create a button that hides itself on click.
Créez un bouton qui se cache lui-même quand on clique dessus.

```online
Like this:
<input type="button" onclick="this.hidden=true" value="Click to hide">
Comme ça:
<input type="button" onclick="this.hidden=true" value="Cliquer pour cacher">
```
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
The answer: `1` and `2`.
La réponse: `1` et `2`.

The first handler triggers, because it's not removed by `removeEventListener`. To remove the handler we need to pass exactly the function that was assigned. And in the code a new function is passed, that looks the same, but is still another function.
Le premier gestionnaire se déclenche, car il n'est pas supprimé par `removeEventListener`. Pour le supprimer, il faut passer en paramètre exactement la fonction qui a servi à le créer. Dans ce code, c'est une nouvelle fonction qui est passée en paramètre, qui est identique mais pas la même.

To remove a function object, we need to store a reference to it, like this:
Pour supprimer un gestionnaire d'un élement, il faut stocker quelque part une référence au gestionnaire, comme ceci:

```js
function handler() {
Expand All @@ -13,4 +13,4 @@ button.addEventListener("click", handler);
button.removeEventListener("click", handler);
```

The handler `button.onclick` works independently and in addition to `addEventListener`.
Le gestionnaire `button.onclick` fonctionne indépendamment et en plus de `addEventListener`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Which handlers run?
# Quel gestionnaire est exécuté?

There's a button in the variable. There are no handlers on it.
Il y a un bouton dans la variable `button`. Il n'a aucun gestionnaire d'événement sur le bouton.

Which handlers run on click after the following code? Which alerts show up?
Quels gestionnaires vont s'exécuter lors d'un clic? Quelles alertes vont s'afficher?

```js no-beautify
button.addEventListener("click", () => alert("1"));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@

First we need to choose a method of positioning the ball.
Tout d'abord, on doit choisir une méthode de positionnement du ballon.

We can't use `position:fixed` for it, because scrolling the page would move the ball from the field.
On ne peut pas utiliser `position:fixed` pour le ballon, car scroller la page ferait sortir le ballon du terrain.

So we should use `position:absolute` and, to make the positioning really solid, make `field` itself positioned.
On devrait donc plutôt utiliser `position:absolute` et, pour consolider tout ça, positioner aussi le terrain `field`.

Then the ball will be positioned relatively to the field:
Puis le ballon est positionné relativement au terrain:

```css
#field {
Expand All @@ -16,36 +16,36 @@ Then the ball will be positioned relatively to the field:

#ball {
position: absolute;
left: 0; /* relative to the closest positioned ancestor (field) */
left: 0; /* relatif au parent le plus proche (le terrain) */
top: 0;
transition: 1s all; /* CSS animation for left/top makes the ball fly */
transition: 1s all; /* Les animations CSS pour gauche/haut fait s'envoler le ballon */
}
```

Next we need to assign the correct `ball.style.left/top`. They contain field-relative coordinates now.
Ensuite, on doit assigner les valeurs correctes pour `ball.style.left/top`. Elles contiennent maintenant les coordonnées relatives au terrain.

Here's the picture:
Voici l'image:

![](move-ball-coords.svg)

We have `event.clientX/clientY` -- window-relative coordinates of the click.
On a `event.clientX/clientY` -- les coordonnées du clic relatives à la fenêtre.

To get field-relative `left` coordinate of the click, we can substract the field left edge and the border width:
Pour récupérer les coordonnées relatives au terrain `left` du clic, on peut soustraire la bordure gauche du terrain et la largeur de la bordure:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft;
```

Normally, `ball.style.left` means the "left edge of the element" (the ball). So if we assign that `left`, then the ball edge, not center, would be under the mouse cursor.
Normalement, `ball.style.left` signifie "la bordure gauche de l'élément" (le ballon). Donc si on assigne cette valeur `left`, alors c'est le bord du ballon, et non son centre, qui seraient à la position du clic.

We need to move the ball half-width left and half-height up to make it center.
On doit déplacer le ballon de la moitié de sa largeur vers la gauche, et de la moitié de sa hauteur vers le haut.

So the final `left` would be:
La valeur finale de `left` serait:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft - ball.offsetWidth/2;
```

The vertical coordinate is calculated using the same logic.
La coordonnée verticale est calculée en suivant la même logique.

Please note that the ball width/height must be known at the time we access `ball.offsetWidth`. Should be specified in HTML or CSS.
Notez que la largeur/hauteur du ballon doivent être connues quand on accède à `ball.offsetWidth`. Elles devraient être spécifiées dans le HTML ou le CSS.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

<body style="height:2000px">

Click on a field to move the ball there.
Cliquez sur le terrain pour déplacer le ballon.
<br>


Expand All @@ -39,29 +39,32 @@
<script>
field.onclick = function(event) {

// window-relative field coordinates
// Coordonnées sur la fenêtre
let fieldCoords = this.getBoundingClientRect();

// the ball has position:absolute, the field: position:relative
// so ball coordinates are relative to the field inner left-upper corner
// Le ballon a position:absolute, le terrain a position:relative
// Les coordonnées du ballon sont donc relatives au coin haut-gauche du terrain
let ballCoords = {
top: event.clientY - fieldCoords.top - field.clientTop - ball.clientHeight / 2,
left: event.clientX - fieldCoords.left - field.clientLeft - ball.clientWidth / 2
};

// prevent crossing the top field boundary
if (ballCoords.top < 0) ballCoords.top = 0;

// prevent crossing the left field boundary
if (ballCoords.left < 0) ballCoords.left = 0;
// Evite de sortir du terrain - haut
if (ballCoords.top < 0) {
ballCoords.top = 0;
}

// Evite de sortir du terrain - left
if (ballCoords.left < 0) {
ballCoords.left = 0;
}

// // prevent crossing the right field boundary
// Evite de sortir du terrain - gauche
if (ballCoords.left + ball.clientWidth > field.clientWidth) {
ballCoords.left = field.clientWidth - ball.clientWidth;
}

// prevent crossing the bottom field boundary
// Evite de sortir du terrain - bas
if (ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

<body style="height:2000px">

Click on a field to move the ball there.
<br> The ball should never leave the field.
Cliquez sur le terrain pour déplacer le ballon.
<br> Le ballon ne devrait jamais sortir du terrain.


<div id="field">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ importance: 5

---

# Move the ball across the field
# Déplacez le ballon sur le terrain

Move the ball across the field to a click. Like this:
Déplacez le ballon sur le terrain lors d'un clic. Comme ceci:

[iframe src="solution" height="260" link]

Requirements:
Pré-requis:

- The ball center should come exactly under the pointer on click (if possible without crossing the field edge).
- CSS-animation is welcome.
- The ball must not cross field boundaries.
- When the page is scrolled, nothing should break.
- Le centre du ballon derait arriver exactement aux coordonnées du clic.
- Les animations CSS sont bienvenues.
- Le ballon ne doit pas sortir du terrain.
- Quand la page scrolle, rien de devrait se casser.

Notes:

- The code should also work with different ball and field sizes, not be bound to any fixed values.
- Use properties `event.clientX/event.clientY` for click coordinates.
- Le code devrait aussi fonctionner avec des ballons ou des terrains de différentes tailles; et ne pas utiliser des coordonnées fixes.
- Utilisez les propriétés `event.clientX/event.clientY` for récupérer les coordonnées du clic.
Original file line number Diff line number Diff line change
@@ -1,47 +1,48 @@

# HTML/CSS
First let's create HTML/CSS.

A menu is a standalone graphical component on the page, so it's better to put it into a single DOM element.
Tout d'abord, on va créer le HTML/CSS.

A list of menu items can be laid out as a list `ul/li`.
Un menu est un composant graphique indépendant sur la page, c'est donc une bonne idée de le mettre dans son propre élément dans le DOM.

Here's the example structure:
Une liste d'options dans un menu peut être affichée comme une liste `ul/li`.

Voici la structure d'exemple:

```html
<div class="menu">
<span class="title">Sweeties (click me)!</span>
<span class="title">Gâteaux (cliquez moi)!</span>
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Tarte aux pommes</li>
<li>Cookies</li>
<li>Brownies</li>
</ul>
</div>
```

We use `<span>` for the title, because `<div>` has an implicit `display:block` on it, and it will occupy 100% of the horizontal width.
On utilise `<span>` pour le titre, car `<div>` a la propriété `display:block` implicitement, et il occupera 100% de la largeur horizontale.

Like this:
Comme ceci:

```html autorun height=50
<div style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</div>
<div style="border: solid red 1px" onclick="alert(1)">Gâteaux (cliquez moi)!</div>
```

So if we set `onclick` on it, then it will catch clicks to the right of the text.
Si on défini `onclick` dessus, il traitera les clics à droite du texte.

As `<span>` has an implicit `display: inline`, it occupies exactly enough place to fit all the text:
Comme `<span>` a la propriété `display: inline` implicitement, il occupe exactement assez de place pour y mettre tout le texte:

```html autorun height=50
<span style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</span>
<span style="border: solid red 1px" onclick="alert(1)">Gâteaux (cliquez moi)!</span>
```

# Toggling the menu
# Changer l'état du menu

Toggling the menu should change the arrow and show/hide the menu list.
Changer l'état du menu devrait modifier la flèche et montrer/cacher le menu.

All these changes are perfectly handled by CSS. In JavaScript we should label the current state of the menu by adding/removing the class `.open`.
Tous ces changements sont parfaitement gérés par CSS. En JavaScript, on devrait indiquer l'état actuel du menu en ajoutant/supprimant la classe CSS `.open`.

Without it, the menu will be closed:
Sans ça, le menu sera fermé:

```css
.menu ul {
Expand All @@ -58,7 +59,7 @@ Without it, the menu will be closed:
}
```

...And with `.open` the arrow changes and the list shows up:
...Et avec `.open`, la flèche change et la liste apparaît:

```css
.menu.open .title::before {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@
<body>

<div id="sweeties" class="menu">
<span class="title">Sweeties (click me)!</span>
<span class="title">Gâteaux (cliquez moi)!</span>
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Tarte aux pommes</li>
<li>Cookies</li>
<li>Brownies</li>
</ul>

</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
</head>
<body>

▶ ▼ Sweeties (click me)!
▶ ▼ Gâteaux (cliquez moi)!
<ul>
<li>Cake</li>
<li>Donut</li>
<li>Honey</li>
<li>Tarte aux pommes</li>
<li>Cookies</li>
<li>Brownies</li>
</ul>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 5

---

# Create a sliding menu
# Créer un menu déroulant

Create a menu that opens/collapses on click:
Créez un menu qui se déroule/s'enroule quand on clique dessus:

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

P.S. HTML/CSS of the source document is to be modified.
Note: Le HTML/CSS sont à modifier.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@

To add the button we can use either `position:absolute` (and make the pane `position:relative`) or `float:right`. The `float:right` has the benefit that the button never overlaps the text, but `position:absolute` gives more freedom. So the choice is yours.
Pour ajouter le bouton, on peut ajouter soit `position:absolute` (et ajouter `position:relative` à chaque message) ou `float:right`. `float:right` a l'avantage que le bouton ne sera jamais surimposé au texte, mais `position:absolute` donne plus de liberté. A vous de choisir.

Then for each pane the code can be like:
Ensuite, pour chaque message, le code pourrait être:
```js
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
```

Then the `<button>` becomes `pane.firstChild`, so we can add a handler to it like this:
Alors le `<button>` devient `pane.firstChild`, on peut donc lui ajouter un gestionnaire comme ceci::

```js
pane.firstChild.onclick = () => pane.remove();
Expand Down
Loading