Skip to content

Commit 7653c34

Browse files
committed
2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave: Translation P.4
1 parent f02c212 commit 7653c34

File tree

4 files changed

+48
-48
lines changed

4 files changed

+48
-48
lines changed
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11

2-
The algorithm looks simple:
3-
1. Put `onmouseover/out` handlers on the element. Also can use `onmouseenter/leave` here, but they are less universal, won't work if we introduce delegation.
4-
2. When a mouse cursor entered the element, start measuring the speed on `mousemove`.
5-
3. If the speed is slow, then run `over`.
6-
4. When we're going out of the element, and `over` was executed, run `out`.
2+
Алгоритм виглядає просто:
3+
1. Додайте обробники `onmouseover/out` на елемент. Тут також можна використовувати `onmouseenter/leave`, але вони менш універсальні, і не працюватимуть, якщо ми використаємо делегування подій.
4+
2. Коли вказівник миші увійшов на елемент, почніть вимірювати швидкість на `mousemove`.
5+
3. Якщо швидкість низька, то запускаємо `over`.
6+
4. Коли вказівник виходить за межі елемента, і `over` закінчила свою роботу, запускаємо `out`.
77

8-
But how to measure the speed?
8+
Але як виміряти швидкість?
99

10-
The first idea can be: run a function every `100ms` and measure the distance between previous and new coordinates. If it's small, then the speed is small.
10+
Перша ідея може бути такою: запускати функцію кожні `100ms` і вимірювати відстань між попередньою та новою координатами. Якщо відстань маленька, то швидкість невелика.
1111

12-
Unfortunately, there's no way to get "current mouse coordinates" in JavaScript. There's no function like `getCurrentMouseCoordinates()`.
12+
На жаль, у JavaScript немає способу отримати поточні координати вказівника миші. Немає таких функцій, як `getCurrentMouseCoordinates()`.
1313

14-
The only way to get coordinates is to listen for mouse events, like `mousemove`, and take coordinates from the event object.
14+
Єдиний спосіб отримати координати -- в обробнику подій миші, наприклад `mousemove`, і брати координати з об’єкта події.
1515

16-
So let's set a handler on `mousemove` to track coordinates and remember them. And then compare them, once per `100ms`.
16+
Отже, давайте додамо обробник на `mousemove`, де відстежемо і запам'ятаємо поточні координати. А далі будемо порівнювати їх раз на `100ms`.
1717

18-
P.S. Please note: the solution tests use `dispatchEvent` to see if the tooltip works right.
18+
P.S. Зверніть увагу: тести рішення використовують `dispatchEvent`, щоб перевірити, чи підказка працює правильно.

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/hoverIntent.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
class HoverIntent {
44

55
constructor({
6-
sensitivity = 0.1, // speed less than 0.1px/ms means "hovering over an element"
7-
interval = 100, // measure mouse speed once per 100ms
6+
sensitivity = 0.1, // швидкість менше 0,1 пікселів/мс означає "наведення вказівника на елемент"
7+
interval = 100, // вимірювати швидкість миші раз на 100ms: обчислити відстань між попередньою та наступною точками
88
elem,
99
over,
1010
out
@@ -15,12 +15,12 @@ class HoverIntent {
1515
this.over = over;
1616
this.out = out;
1717

18-
// make sure "this" is the object in event handlers.
18+
// переконайтеся, що "this" є нашми об’єктом в обробниках подій.
1919
this.onMouseMove = this.onMouseMove.bind(this);
2020
this.onMouseOver = this.onMouseOver.bind(this);
2121
this.onMouseOut = this.onMouseOut.bind(this);
2222

23-
// and in time-measuring function (called from setInterval)
23+
// і у функції вимірювання часу (викликається з setInterval)
2424
this.trackSpeed = this.trackSpeed.bind(this);
2525

2626
elem.addEventListener("mouseover", this.onMouseOver);
@@ -32,16 +32,16 @@ class HoverIntent {
3232
onMouseOver(event) {
3333

3434
if (this.isOverElement) {
35-
// if we're over the element, then ignore the event
36-
// we are already measuring the speed
35+
// якщо ми знову пройшли над елементом, ігноруємо подію
36+
// ми вже вимірюємо швидкість
3737
return;
3838
}
3939

4040
this.isOverElement = true;
4141

42-
// after every mousemove we'll be check the distance
43-
// between the previous and the current mouse coordinates
44-
// if it's less than sensivity, then the speed is slow
42+
// після кожного руху миші ми будемо перевіряти відстань
43+
// між попередньою та поточною координатами миші
44+
// якщо менше ніж значення sensitivity, швидкість повільна
4545

4646
this.prevX = event.pageX;
4747
this.prevY = event.pageY;
@@ -52,13 +52,13 @@ class HoverIntent {
5252
}
5353

5454
onMouseOut(event) {
55-
// if left the element
55+
// якщо залишили елемент
5656
if (!event.relatedTarget || !elem.contains(event.relatedTarget)) {
5757
this.isOverElement = false;
5858
this.elem.removeEventListener('mousemove', this.onMouseMove);
5959
clearInterval(this.checkSpeedInterval);
6060
if (this.isHover) {
61-
// if there was a stop over the element
61+
// якщо була зупинка над елементом
6262
this.out.call(this.elem, event);
6363
this.isHover = false;
6464
}
@@ -76,7 +76,7 @@ class HoverIntent {
7676
let speed;
7777

7878
if (!this.lastTime || this.lastTime == this.prevTime) {
79-
// cursor didn't move
79+
// вказівник не рухався
8080
speed = 0;
8181
} else {
8282
speed = Math.sqrt(
@@ -90,7 +90,7 @@ class HoverIntent {
9090
this.isHover = true;
9191
this.over.call(this.elem);
9292
} else {
93-
// speed fast, remember new coordinates as the previous ones
93+
// якщо рухається швидко, записуємо нові координати як попередні
9494
this.prevX = this.lastX;
9595
this.prevY = this.lastY;
9696
this.prevTime = this.lastTime;

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/source.view/hoverIntent.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
'use strict';
22

3-
// Here's a brief sketch of the class
4-
// with things that you'll need anyway
3+
// Ось короткий нарис класу
4+
// з речами, які все одно знадобляться
55
class HoverIntent {
66

77
constructor({
8-
sensitivity = 0.1, // speed less than 0.1px/ms means "hovering over an element"
9-
interval = 100, // measure mouse speed once per 100ms: calculate the distance between previous and next points
8+
sensitivity = 0.1, // швидкість менше 0,1 пікселів/мс означає "наведення вказівника на елемент"
9+
interval = 100, // вимірювати швидкість миші раз на 100ms: обчислити відстань між попередньою та наступною точками
1010
elem,
1111
over,
1212
out
@@ -17,16 +17,16 @@ class HoverIntent {
1717
this.over = over;
1818
this.out = out;
1919

20-
// make sure "this" is the object in event handlers.
20+
// переконайтеся, що "this" є нашим об’єктом в обробниках подій.
2121
this.onMouseMove = this.onMouseMove.bind(this);
2222
this.onMouseOver = this.onMouseOver.bind(this);
2323
this.onMouseOut = this.onMouseOut.bind(this);
2424

25-
// assign the handlers
25+
// додамо обробники
2626
elem.addEventListener("mouseover", this.onMouseOver);
2727
elem.addEventListener("mouseout", this.onMouseOut);
2828

29-
// continue from this point
29+
// ми зробили що могли, далі ви вже самі ;)
3030

3131
}
3232

@@ -44,8 +44,8 @@ class HoverIntent {
4444

4545

4646
destroy() {
47-
/* your code to "disable" the functionality, remove all handlers */
48-
/* it's needed for the tests to work */
47+
/* ваш код, щоб "вимкнути" функціональність, видаліть усі обробники */
48+
/* це потрібно для роботи тестів */
4949
}
5050

5151
}

2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/task.md

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

33
---
44

5-
# "Smart" tooltip
5+
# "Розумна" підказка
66

7-
Write a function that shows a tooltip over an element only if the visitor moves the mouse *to it*, but not *through it*.
7+
Напишіть функцію, яка показуватиме спливаючу підказку над елементом лише тоді, коли відвідувач прямую вказівник миші безпосередньо *до нього*, але не *крізь нього*.
88

9-
In other words, if the visitor moves the mouse to the element and stops there -- show the tooltip. And if they just moved the mouse through, then no need, who wants extra blinking?
9+
Іншими словами, якщо відвідувач наводить вказівник миші на елемент і зупиняється на ньому, показується підказка. І якщо просто провели мишею, то показувати підказку взагалі не потрібно, кому може сподобатись додаткове миготіння?
1010

11-
Technically, we can measure the mouse speed over the element, and if it's slow then we assume that it comes "over the element" and show the tooltip, if it's fast -- then we ignore it.
11+
Технічно ми можемо виміряти швидкість я кою рухається вказівник над елементом, і якщо вона швидкість повільна, ми припускаємо, що вказівник проходить "над елементом" і показуємо спливаючу підказку, якщо вона швидка, ми ігноруємо цей прохід вказівника.
1212

13-
Make a universal object `new HoverIntent(options)` for it.
13+
У цьому завданні ви маєте описати клас і створити універсальний об’єкт `new HoverIntent(options)`
1414

15-
Its `options`:
16-
- `elem` -- element to track.
17-
- `over` -- a function to call if the mouse came to the element: that is, it moves slowly or stopped over it.
18-
- `out` -- a function to call when the mouse leaves the element (if `over` was called).
15+
Його `options`:
16+
- `elem` -- елемент для відстеження.
17+
- `over` -- функція, яка викликається, якщо миша підійшла до елемента: тобто вона повільно рухається або зупиняється над ним.
18+
- `out` -- функція для виклику, коли вказівник залишає елемент (якщо було викликано `over`).
1919

20-
An example of using such object for the tooltip:
20+
Приклад використання такого об'єкта для підказки:
2121

2222
```js
23-
// a sample tooltip
23+
// зразок підказки
2424
let tooltip = document.createElement('div');
2525
tooltip.className = "tooltip";
2626
tooltip.innerHTML = "Tooltip";
2727

28-
// the object will track mouse and call over/out
28+
// об'єкт буде стежити за мишею та викликатиме over/out
2929
new HoverIntent({
3030
elem,
3131
over() {
@@ -39,10 +39,10 @@ new HoverIntent({
3939
});
4040
```
4141

42-
The demo:
42+
Як це має працювати:
4343

4444
[iframe src="solution" height=140]
4545

46-
If you move the mouse over the "clock" fast then nothing happens, and if you do it slow or stop on them, then there will be a tooltip.
46+
Якщо наводити мишу на елемент "clock" швидко, то нічого не відбувається, а якщо ви робите це повільно або зупиняєтеся на ньому, то з'явиться спливаюча підказка.
4747

48-
Please note: the tooltip doesn't "blink" when the cursor moves between the clock subelements.
48+
Зверніть увагу: спливаюча підказка не "блимає", коли вказівник переміщується між вкладенними елементами всередині "clock".

0 commit comments

Comments
 (0)