Skip to content

Commit fde9b08

Browse files
authored
Merge pull request #292 from Regnised/feature/introduction-browser-events
Feature/introduction browser events
2 parents 8054efd + dbf1f1b commit fde9b08

File tree

25 files changed

+292
-292
lines changed

25 files changed

+292
-292
lines changed

2-ui/2-events/01-introduction-browser-events/01-hide-other/solution.view/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77

88
<body>
99

10-
<input type="button" id="hider" value="Click to hide the text" />
10+
<input type="button" id="hider" value="Натисніть, щоб текст зник" />
1111

12-
<div id="text">Text</div>
12+
<div id="text">Текст</div>
1313

1414
<script>
15-
// Here it doesn't matter how we hide the text,
16-
// could also use style.display:
15+
// Тут не має значення, як ми приховуємо текст
16+
// Також можна використати style.display:
1717
document.getElementById('hider').onclick = function() {
1818
document.getElementById('text').hidden = true;
1919
}

2-ui/2-events/01-introduction-browser-events/01-hide-other/source.view/index.html

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77

88
<body>
99

10-
<input type="button" id="hider" value="Click to hide the text" />
10+
<input type="button" id="hider" value="Натисніть, щоб текст зник" />
1111

12-
<div id="text">Text</div>
12+
<div id="text">Текст</div>
1313

1414
<script>
15-
/* your code */
15+
/* ваш код */
1616
</script>
1717

1818
</body>

2-ui/2-events/01-introduction-browser-events/01-hide-other/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ importance: 5
22

33
---
44

5-
# Hide on click
5+
# Приховати елемент після натискання кнопки
66

7-
Add JavaScript to the `button` to make `<div id="text">` disappear when we click it.
7+
Напишіть такий JavaScript, щоб після натискання на кнопку `button`, елемент `<div id="text">` зникав.
88

9-
The demo:
9+
Демонстрація роботи:
1010

1111
[iframe border=1 src="solution" height=80]
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
Can use `this` in the handler to reference "the element itself" here:
1+
Можемо використати `this` в обробнику для доступу до самого елемента:
22

33
```html run height=50
4-
<input type="button" onclick="this.hidden=true" value="Click to hide">
4+
<input type="button" onclick="this.hidden=true" value="Сховати">
55
```

2-ui/2-events/01-introduction-browser-events/02-hide-self-onclick/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Hide self
5+
# Сховати себе
66

7-
Create a button that hides itself on click.
7+
Напишіть такий код, щоб після натискання на кнопку, вона зникала.
88

99
```online
10-
Like this:
11-
<input type="button" onclick="this.hidden=true" value="Click to hide">
10+
Наприклад:
11+
<input type="button" onclick="this.hidden=true" value="Сховати">
1212
```
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
The answer: `1` and `2`.
1+
Відповідь: `1` і `2`.
22

3-
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.
3+
Перший обробник спрацює, тому що він не був вилучений методом `removeEventListener`. Щоб видалити обробник, необхідно передати саме ту функцію, яка була призначена як обробник. Попри те, що код ідентичний, в `removeEventListener` передається нова, інша функція.
44

5-
To remove a function object, we need to store a reference to it, like this:
5+
Щоб видалити функцію-обробник, потрібно десь зберегти посилання на неї, наприклад:
66

77
```js
88
function handler() {
@@ -13,4 +13,4 @@ button.addEventListener("click", handler);
1313
button.removeEventListener("click", handler);
1414
```
1515

16-
The handler `button.onclick` works independently and in addition to `addEventListener`.
16+
Обробник `button.onclick` спрацює все одно. Разом з `addEventListener`.

2-ui/2-events/01-introduction-browser-events/03-which-handlers-run/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
importance: 5
1+
важливість: 5
22

33
---
44

5-
# Which handlers run?
5+
# Який обробник запуститься?
66

7-
There's a button in the variable. There are no handlers on it.
7+
У змінній `button` знаходиться кнопка. Спочатку на ній немає обробників.
88

9-
Which handlers run on click after the following code? Which alerts show up?
9+
Який з обробників запуститься? Що буде виведено під час кліку після виконання коду?
1010

1111
```js no-beautify
1212
button.addEventListener("click", () => alert("1"));
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11

2-
First we need to choose a method of positioning the ball.
2+
Спочатку ми маємо вибрати метод позиціювання м’яча.
33

4-
We can't use `position:fixed` for it, because scrolling the page would move the ball from the field.
4+
Ми не можемо використати `position:fixed` для цього, оскільки прокручування сторінки переміщатиме м’яч поля.
55

6-
So we should use `position:absolute` and, to make the positioning really solid, make `field` itself positioned.
6+
Правильніше використовувати `position:absolute` і, щоб зробити позиціювання справді надійним, зробимо саме поле `field` позиціонованим.
77

8-
Then the ball will be positioned relatively to the field:
8+
Тоді м’яч буде позиціонований щодо поля:
99

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

1717
#ball {
1818
position: absolute;
19-
left: 0; /* relative to the closest positioned ancestor (field) */
19+
left: 0; /* по відношенню до найближчого розташованого предка (field) */
2020
top: 0;
21-
transition: 1s all; /* CSS animation for left/top makes the ball fly */
21+
transition: 1s all; /* CSS-анімація для значень left/top робить пересування м’яча плавним */
2222
}
2323
```
2424

25-
Next we need to assign the correct `ball.style.left/top`. They contain field-relative coordinates now.
25+
Далі ми маємо призначити коректні значення `ball.style.left/top`. Зараз вони містять координати щодо поля.
2626

27-
Here's the picture:
27+
Як на зображенні:
2828

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

31-
We have `event.clientX/clientY` -- window-relative coordinates of the click.
31+
Ми маємо `event.clientX/clientY` -- координати натискання мишки щодо вікна браузера.
3232

33-
To get field-relative `left` coordinate of the click, we can substract the field left edge and the border width:
33+
Щоб отримати значення `left` для м’яча після натискання мишки щодо поля, ми повинні від координати натискання мишки відняти координату лівого краю поля та ширину межі:
3434

3535
```js
3636
let left = event.clientX - fieldCoords.left - field.clientLeft;
3737
```
3838

39-
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.
39+
Значення `ball.style.left` означає «лівий край елемента» (м’яча). І якщо ми призначимо такий `left` для м’яча, то його ліва межа, а не центр, буде під курсором миші.
4040

41-
We need to move the ball half-width left and half-height up to make it center.
41+
Нам потрібно зрушити м'яч на половину його висоти вгору та половину його ширини вліво, щоб центр м’яча точно збігався з точкою натискання мишки.
4242

43-
So the final `left` would be:
43+
У результаті значення для `left` буде таким:
4444

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

49-
The vertical coordinate is calculated using the same logic.
49+
Вертикальна координата обчислюватиметься за тією ж логікою.
5050

51-
Please note that the ball width/height must be known at the time we access `ball.offsetWidth`. Should be specified in HTML or CSS.
51+
Слід пам’ятати, що ширина та висота м’яча має бути відома в той момент, коли ми отримуємо значення `ball.offsetWidth`. Це значення може бути задано в HTML або CSS.

2-ui/2-events/01-introduction-browser-events/04-move-ball-field/solution.view/index.html

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
<body style="height:2000px">
2929

30-
Click on a field to move the ball there.
30+
Натисніть поле, щоб перемістити м’яч.
3131
<br>
3232

3333

@@ -39,29 +39,29 @@
3939
<script>
4040
field.onclick = function(event) {
4141

42-
// window-relative field coordinates
42+
// координати поля щодо вікна браузера
4343
let fieldCoords = this.getBoundingClientRect();
4444

45-
// the ball has position:absolute, the field: position:relative
46-
// so ball coordinates are relative to the field inner left-upper corner
45+
// м’яч має абсолютне позиціювання (position:absolute), поле -- відносне (position:relative)
46+
// таким чином, координати м’яча розраховуються відносно внутрішнього, верхнього лівого кута поля.
4747
let ballCoords = {
4848
top: event.clientY - fieldCoords.top - field.clientTop - ball.clientHeight / 2,
4949
left: event.clientX - fieldCoords.left - field.clientLeft - ball.clientWidth / 2
5050
};
5151

52-
// prevent crossing the top field boundary
52+
// забороняємо перетинати верхню межу поля
5353
if (ballCoords.top < 0) ballCoords.top = 0;
5454

55-
// prevent crossing the left field boundary
55+
// забороняємо перетинати ліву межу поля
5656
if (ballCoords.left < 0) ballCoords.left = 0;
5757

5858

59-
// // prevent crossing the right field boundary
59+
// забороняємо перетинати праву межу поля
6060
if (ballCoords.left + ball.clientWidth > field.clientWidth) {
6161
ballCoords.left = field.clientWidth - ball.clientWidth;
6262
}
6363

64-
// prevent crossing the bottom field boundary
64+
// забороняємо перетинати нижню межу поля
6565
if (ballCoords.top + ball.clientHeight > field.clientHeight) {
6666
ballCoords.top = field.clientHeight - ball.clientHeight;
6767
}

2-ui/2-events/01-introduction-browser-events/04-move-ball-field/source.view/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616

1717
<body style="height:2000px">
1818

19-
Click on a field to move the ball there.
20-
<br> The ball should never leave the field.
19+
Натисніть поле, щоб перемістити м’яч.
20+
<br> М’яч ніколи не повинен покидати поля.
2121

2222

2323
<div id="field">

2-ui/2-events/01-introduction-browser-events/04-move-ball-field/task.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@ importance: 5
22

33
---
44

5-
# Move the ball across the field
5+
# Пересуньте м’яч по полю
66

7-
Move the ball across the field to a click. Like this:
7+
Нехай м’яч переміщається при натисканні на поле, туди, де був клік, ось так:
88

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

11-
Requirements:
11+
Вимоги:
1212

13-
- The ball center should come exactly under the pointer on click (if possible without crossing the field edge).
14-
- CSS-animation is welcome.
15-
- The ball must not cross field boundaries.
16-
- When the page is scrolled, nothing should break.
13+
- Центр м’яча повинен збігатися з курсором миші (якщо це можливо без перетину країв поля);
14+
- CSS-анімація бажана, але не є обов’язковою;
15+
- М’яч у жодному разі не повинен перетинати межі поля;
16+
- При прокручуванні сторінки нічого не повинно ламатися;
1717

18-
Notes:
18+
Нотатки:
1919

20-
- The code should also work with different ball and field sizes, not be bound to any fixed values.
21-
- Use properties `event.clientX/event.clientY` for click coordinates.
20+
- Код повинен уміти працювати з різними розмірами м’яча та поля, не прив’язуватися до будь-яких фіксованих значень.
21+
- Використовуйте властивості `event.clientX/event.clientY`, щоб вирахувати координати миші при кліці.

2-ui/2-events/01-introduction-browser-events/05-sliding-menu/solution.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,47 @@
11

22
# HTML/CSS
3-
First let's create HTML/CSS.
3+
Для початку створимо розмітку HTML/CSS нашого меню.
44

5-
A menu is a standalone graphical component on the page, so it's better to put it into a single DOM element.
5+
Меню -- це окремий графічний компонент на сторінці, тому його краще винести в окремий DOM-елемент.
66

7-
A list of menu items can be laid out as a list `ul/li`.
7+
Список пунктів меню може бути представлений у вигляді списку `ul/li`.
88

9-
Here's the example structure:
9+
Приклад HTML структури:
1010

1111
```html
1212
<div class="menu">
13-
<span class="title">Sweeties (click me)!</span>
13+
<span class="title">Солодощі (тисни на мене)!</span>
1414
<ul>
15-
<li>Cake</li>
16-
<li>Donut</li>
17-
<li>Honey</li>
15+
<li>Тістечко</li>
16+
<li>Пончик</li>
17+
<li>Мед</li>
1818
</ul>
1919
</div>
2020
```
2121

22-
We use `<span>` for the title, because `<div>` has an implicit `display:block` on it, and it will occupy 100% of the horizontal width.
22+
Для заголовка ми використовуємо тег `<span>`, тому що `<div>`, як і будь-який блоковий елемент, має приховану властивість `display:block`, це означає, що він має 100% ширину.
2323

24-
Like this:
24+
Наприклад:
2525

2626
```html autorun height=50
27-
<div style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</div>
27+
<div style="border: solid red 1px" onclick="alert(1)">Солодощі (тисни мене)!</div>
2828
```
2929

30-
So if we set `onclick` on it, then it will catch clicks to the right of the text.
30+
Таким чином, якщо ми додамо обробник події в `onclick`, то він буде спрацьовувати на клік на всій ширині меню.
3131

32-
As `<span>` has an implicit `display: inline`, it occupies exactly enough place to fit all the text:
32+
Оскільки `<span>` має неявну властивість `display: inline`, він займає тільки стільки місця, щоб умістити весь текст:
3333

3434
```html autorun height=50
35-
<span style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</span>
35+
<span style="border: solid red 1px" onclick="alert(1)">Солодощі (тисни мене)!</span>
3636
```
3737

38-
# Toggling the menu
38+
# Перемикання меню
3939

40-
Toggling the menu should change the arrow and show/hide the menu list.
40+
Функціонал перемикання меню повиннен змінювати стрілку та приховувати або показувати список елементів меню.
4141

42-
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`.
42+
Всі ці зміни можна реалізувати засобами CSS. За допомогою JavaScript ми будемо змінювати вигляд меню, додаючи або видаляючи клас `.open`.
4343

44-
Without it, the menu will be closed:
44+
Без класу `.open` меню буде закритим:
4545

4646
```css
4747
.menu ul {
@@ -58,7 +58,7 @@ Without it, the menu will be closed:
5858
}
5959
```
6060

61-
...And with `.open` the arrow changes and the list shows up:
61+
...А з класом `.open` стрілка зміниться і список буде показано:
6262

6363
```css
6464
.menu.open .title::before {

2-ui/2-events/01-introduction-browser-events/05-sliding-menu/solution.view/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@
3535
<body>
3636

3737
<div id="sweeties" class="menu">
38-
<span class="title">Sweeties (click me)!</span>
38+
<span class="title">Солодощі (тисни на мене)!</span>
3939
<ul>
40-
<li>Cake</li>
41-
<li>Donut</li>
42-
<li>Honey</li>
40+
<li>Тістечко</li>
41+
<li>Пончик</li>
42+
<li>Мед</li>
4343
</ul>
4444

4545
</div>

2-ui/2-events/01-introduction-browser-events/05-sliding-menu/source.view/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
</head>
66
<body>
77

8-
▶ ▼ Sweeties (click me)!
8+
▶ ▼ Солодощі (тисни на мене)!
99
<ul>
10-
<li>Cake</li>
11-
<li>Donut</li>
12-
<li>Honey</li>
10+
<li>Тістечко</li>
11+
<li>Пончик</li>
12+
<li>Мед</li>
1313
</ul>
1414

1515
</body>

2-ui/2-events/01-introduction-browser-events/05-sliding-menu/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ importance: 5
22

33
---
44

5-
# Create a sliding menu
5+
# Створіть меню, що розкривається
66

7-
Create a menu that opens/collapses on click:
7+
Створіть меню, яке відкривається/згортається після кліку:
88

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

11-
P.S. HTML/CSS of the source document is to be modified.
11+
P.S. HTML/CSS вихідного документа можна і треба змінювати.

2-ui/2-events/01-introduction-browser-events/06-hide-message/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11

2-
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.
2+
Щоб додати кнопку закриття, ми можемо використовувати або `position:absolute` (і зробити плитку (pane) `position:relative`) або `float:right`. Перевага варіанта з `float:right` у тому, що кнопка закриття ніколи не перекриє текст, але варіант `position:absolute` дає більше свободи для дій. Загалом вибір за вами.
33

4-
Then for each pane the code can be like:
4+
Тоді для кожного повідомлення(pane) код може бути таким:
55
```js
66
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
77
```
88

9-
Then the `<button>` becomes `pane.firstChild`, so we can add a handler to it like this:
9+
Елемент `<button>` стає `pane.firstChild`, таким чином ми можемо додати до нього обробник події:
1010

1111
```js
1212
pane.firstChild.onclick = () => pane.remove();

0 commit comments

Comments
 (0)