◐ Shell
clean mode source ↗

Browser default actions by OlhaBrozhenets · Pull Request #264 · javascript-tutorial/uk.javascript.info

Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
When the browser reads the `on*` attribute like `onclick`, it creates the handler from its content.
Коли браузер зчитує атрибут `on*`, як `onclick`, він створює обробник із його вмісту.

For `onclick="handler()"` the function will be:
Для `onclick="handler()"` функція буде:

```js
function(event) {
handler() // the content of onclick
handler() // вміст onclick
}
```

Now we can see that the value returned by `handler()` is not used and does not affect the result.
Тепер ми бачимо, що значення, яке повертає `handler()`, не використовується і не впливає на результат.

The fix is simple:
Виправлення просте:

```html run
<script>
Expand All @@ -23,7 +23,7 @@ The fix is simple:
<a href="https://w3.org" onclick="*!*return handler()*/!*">w3.org</a>
```

Also we can use `event.preventDefault()`, like this:
Також ми можемо використовувати `event.preventDefault()`, наприклад:

```html run
<script>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 3

---

# Why "return false" doesn't work?
# Чому "return false" не працює?

Why in the code below `return false` doesn't work at all?
Чому в коді нижче `return false` взагалі не працює?

```html autorun run
<script>
Expand All @@ -14,9 +14,9 @@ Why in the code below `return false` doesn't work at all?
}
</script>

<a href="https://w3.org" onclick="handler()">the browser will go to w3.org</a>
<a href="https://w3.org" onclick="handler()">браузер перейде на w3.org</a>
```

The browser follows the URL on click, but we don't want it.
Браузер переходить за URL-адресою після кліку, але нам це не потрібно.

How to fix?
Як це виправити?
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
That's a great use of the event delegation pattern.
Це чудове використання шаблону делегування подій.

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).
У реальному житті замість того, щоб запитувати, ми можемо надіслати запит на «реєстрацію» на сервер, який зберігає інформацію про те, куди пішов відвідувач. Або ми можемо завантажити вміст і показати його прямо на сторінці (якщо це дозволено).

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.
Все, що нам потрібно, це зловити `contents.onclick` і використати `confirm`, щоб запитати користувача. Хорошою ідеєю було б використовувати `link.getAttribute('href')` замість `link.href` для URL-адреси. Подробиці дивіться у рішенні.
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
<fieldset id="contents">
<legend>#contents</legend>
<p>
How about to read <a href="https://wikipedia.org">Wikipedia</a> or visit <a href="https://w3.org"><i>W3.org</i></a> and learn about modern standards?
Як щодо того, щоб почитати <a href="https://wikipedia.org">Вікіпедію</a> або відвідати <a href="https://w3.org"><i>W3.org</i></a> і дізнатися про сучасні стандарти?
</p>
</fieldset>

<script>
contents.onclick = function(event) {

function handleLink(href) {
let isLeaving = confirm(`Leave for ${href}?`);
let isLeaving = confirm(`Перейти на ${href}?`);
if (!isLeaving) return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<fieldset id="contents">
<legend>#contents</legend>
<p>
How about to read <a href="https://wikipedia.org">Wikipedia</a> or visit <a href="https://w3.org"><i>W3.org</i></a> and learn about modern standards?
Як щодо того, щоб почитати <a href="https://wikipedia.org">Вікіпедію</a> або відвідати <a href="https://w3.org"><i>W3.org</i></a> і дізнатися про сучасні стандарти?
</p>
</fieldset>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ importance: 5

---

# Catch links in the element
# Зловіть посилання

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.
Зробіть так, щоб усі посилання всередині елемента з `id="contents"` запитали у користувача, чи дійсно він хоче вийти. І якщо ні, то не переходьте за посиланням.

Like this:
Ось таким чином:

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

Details:
Детальніше:

- 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 `<a href=".."><i>...</i></a>`.
- HTML всередині елемента може бути завантажений або динамічно відновлений в будь-який час, тому ми не можемо знайти всі посилання та розмістити на них обробники. Використовуйте делегування подій.
- Вміст може мати вкладені теги. Внутрішні посилання також, як-от `<a href=".."><i>...</i></a>`.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
The solution is to assign the handler to the container and track clicks. If a click is on the `<a>` link, then change `src` of `#largeImg` to the `href` of the thumbnail.
Рішення полягає в тому, щоб призначити обробник контейнеру та відстежувати кліки. Якщо клік відбувається на посилання `<a>`, змініть `src` для `#largeImg` на `href` мініатюри.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>

<head>
<title>Gallery</title>
<title>Галерея</title>
<link rel="stylesheet" href="gallery.css">
<meta charset="utf-8">
</head>
Expand All @@ -12,21 +12,21 @@
<p><img id="largeImg" src="https://en.js.cx/gallery/img1-lg.jpg" alt="Large image"></p>

<ul id="thumbs">
<!-- the browser shows a small built-in tooltip on hover with the text from "title" attribute -->
<!-- браузер показує невелику вбудовану підказку при наведенні курсора з текстом атрибута "title" -->
<li>
<a href="https://en.js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://en.js.cx/gallery/img2-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img2-lg.jpg" title="Зображення 2"><img src="https://en.js.cx/gallery/img2-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://en.js.cx/gallery/img3-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img3-lg.jpg" title="Зображення 3"><img src="https://en.js.cx/gallery/img3-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://en.js.cx/gallery/img4-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img4-lg.jpg" title="Зображення 4"><img src="https://en.js.cx/gallery/img4-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://en.js.cx/gallery/img5-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img5-lg.jpg" title="Зображення 5"><img src="https://en.js.cx/gallery/img5-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://en.js.cx/gallery/img6-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img6-lg.jpg" title="Зображення 6"><img src="https://en.js.cx/gallery/img6-thumb.jpg"></a>
</li>
</ul>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>

<head>
<title>Gallery</title>
<title>Галерея</title>
<link rel="stylesheet" href="gallery.css">
<meta charset="utf-8">
</head>
Expand All @@ -12,21 +12,21 @@
<p><img id="largeImg" src="https://en.js.cx/gallery/img1-lg.jpg" alt="Large image"></p>

<ul id="thumbs">
<!-- the browser shows a small built-in tooltip on hover with the text from "title" attribute -->
<!-- браузер показує невелику вбудовану підказку при наведенні курсора з текстом атрибута "title" -->
<li>
<a href="https://en.js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://en.js.cx/gallery/img2-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img2-lg.jpg" title="Зображення 2"><img src="https://en.js.cx/gallery/img2-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://en.js.cx/gallery/img3-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img3-lg.jpg" title="Зображення 3"><img src="https://en.js.cx/gallery/img3-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://en.js.cx/gallery/img4-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img4-lg.jpg" title="Зображення 4"><img src="https://en.js.cx/gallery/img4-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://en.js.cx/gallery/img5-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img5-lg.jpg" title="Зображення 5"><img src="https://en.js.cx/gallery/img5-thumb.jpg"></a>
</li>
<li>
<a href="https://en.js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://en.js.cx/gallery/img6-thumb.jpg"></a>
<a href="https://en.js.cx/gallery/img6-lg.jpg" title="Зображення 6"><img src="https://en.js.cx/gallery/img6-thumb.jpg"></a>
</li>
</ul>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 5

---

# Image gallery
# Галерея зображень

Create an image gallery where the main image changes by the click on a thumbnail.
Створіть галерею зображень, де основне зображення змінюється натисканням на мініатюру.

Like this:
Ось таким чином:

[iframe src="solution" height=600]

P.S. Use event delegation.
P.S. Використовуйте делегування подій.