Skip to content

Commit aaf5ef4

Browse files
authored
Merge pull request #620 from dolgachio/master
3-mousemove-mouseover-mouseout-mouseenter-mouseleave
2 parents c2de95c + 6b02e54 commit aaf5ef4

File tree

9 files changed

+187
-187
lines changed

9 files changed

+187
-187
lines changed

Diff for: 2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html

+17-17
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<style>
77
body {
88
height: 2000px;
9-
/* the tooltip should work after page scroll too */
9+
/* спливаюча підказка також має працювати після прокручування сторінки */
1010
}
1111

1212
.tooltip {
@@ -49,42 +49,42 @@
4949
<body>
5050

5151

52-
<div data-tooltip="Here is the house interior" id="house">
53-
<div data-tooltip="Here is the roof" id="roof"></div>
52+
<div data-tooltip="Ось – інтер’єр будинку" id="house">
53+
<div data-tooltip="Ось – дах" id="roof"></div>
5454

55-
<p>Once upon a time there was a mother pig who had three little pigs.</p>
55+
<p>Жила-була мама-свиня, у якої було троє поросят.</p>
5656

57-
<p>The three little pigs grew so big that their mother said to them, "You are too big to live here any longer. You must go and build houses for yourselves. But take care that the wolf does not catch you."</p>
57+
<p>Троє поросят виросли такі великі, що їхня мати сказала їм: "Ви занадто великі, щоб жити тут далі. Ви повинні йти і будувати собі будинки. Але бережіть себе, щоб вовк вас не спіймав."</p>
5858

59-
<p>The three little pigs set off. "We will take care that the wolf does not catch us," they said.</p>
59+
<p>Троє поросят рушили. "Будемо берегти один одного, щоб вовк нас не спіймав", - сказали вони.</p>
6060

61-
<p>Soon they met a man. <a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a></p>
61+
<p>Незабаром вони зустріли чоловіка.<a href="https://uk.wikipedia.org/wiki/Троє_поросят" data-tooltip="Читайте далі">Наведіть на мене мишу</a></p>
6262

6363
</div>
6464

6565
<script>
6666
let tooltip;
6767

6868
document.onmouseover = function(event) {
69-
// important: a fast-moving mouse may "jump" right to a child on an annotated node, skipping the parent
70-
// so mouseover may happen on a child.
69+
// важливо: миша, що швидко рухається, може "стрибнути" прямо до дочірнього вузла, пропускаючи батьківський
70+
// тому mouseover може статися на дочірньому елементі.
7171

7272
let anchorElem = event.target.closest('[data-tooltip]');
7373

7474
if (!anchorElem) return;
7575

76-
// show tooltip and remember it
76+
// показати підказку та запам'ятати її
7777
tooltip = showTooltip(anchorElem, anchorElem.dataset.tooltip);
7878
}
7979

8080
document.onmouseout = function() {
81-
// it is possible that mouseout triggered, but we're still inside the element
82-
// (its target was inside, and it bubbled)
83-
// but in this case we'll have an immediate mouseover,
84-
// so the tooltip will be destroyed and shown again
81+
// можливо, спрацював mouseout, але ми все ще всередині елемента
82+
// (target цієї події всередині, і подія спливає)
83+
// але в цьому випадку ми маємо негайне спрацювання події mouseover,
84+
// тому спливаючу підказку буде знищено та показано знову
8585
//
86-
// luckily, the "blinking" won't be visible,
87-
// as both events happen almost at the same time
86+
// на щастя, "миготіння" не буде видно,
87+
// оскільки обидві події відбуваються майже одночасно
8888
if (tooltip) {
8989
tooltip.remove();
9090
tooltip = false;
@@ -101,7 +101,7 @@
101101

102102
let coords = anchorElem.getBoundingClientRect();
103103

104-
// position the tooltip over the center of the element
104+
// розмістити підказку над центром елемента
105105
let left = coords.left + (anchorElem.offsetWidth - tooltipElem.offsetWidth) / 2;
106106
if (left < 0) left = 0;
107107

Diff for: 2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html

+8-8
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<style>
77
body {
88
height: 2000px;
9-
/* the tooltip should work after page scroll too */
9+
/* спливаюча підказка також має працювати після прокручування сторінки */
1010
}
1111

1212
.tooltip {
@@ -49,21 +49,21 @@
4949
<body>
5050

5151

52-
<div data-tooltip="Here is the house interior" id="house">
53-
<div data-tooltip="Here is the roof" id="roof"></div>
52+
<div data-tooltip="Ось – інтер’єр будинку" id="house">
53+
<div data-tooltip="Ось – дах" id="roof"></div>
5454

55-
<p>Once upon a time there was a mother pig who had three little pigs.</p>
55+
<p>Жила-була мама-свиня, у якої було троє поросят.</p>
5656

57-
<p>The three little pigs grew so big that their mother said to them, "You are too big to live here any longer. You must go and build houses for yourselves. But take care that the wolf does not catch you."</p>
57+
<p>Троє поросят виросли такі великі, що їхня мати сказала їм: "Ви занадто великі, щоб жити тут далі. Ви повинні йти і будувати собі будинки. Але бережіть себе, щоб вовк вас не спіймав."</p>
5858

59-
<p>The three little pigs set off. "We will take care that the wolf does not catch us," they said.</p>
59+
<p>Троє поросят рушили. "Будемо берегти один одного, щоб вовк нас не спіймав", - сказали вони.</p>
6060

61-
<p>Soon they met a man. <a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a></p>
61+
<p>Незабаром вони зустріли чоловіка.<a href="https://uk.wikipedia.org/wiki/Троє_поросят" data-tooltip="Читайте далі">Наведіть на мене мишу</a></p>
6262

6363
</div>
6464

6565
<script>
66-
// ...your code...
66+
// ...ваш код...
6767
</script>
6868

6969
</body>

Diff for: 2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/task.md

+9-9
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@ importance: 5
22

33
---
44

5-
# Improved tooltip behavior
5+
# Покращена поведінка спливаючої підказки
66

7-
Write JavaScript that shows a tooltip over an element with the attribute `data-tooltip`. The value of this attribute should become the tooltip text.
7+
Напишіть JavaScript, який покаже спливаючу підказку над елементом із атрибутом `data-tooltip`. Значення цього атрибута має стати текстом підказки.
88

9-
That's like the task <info:task/behavior-tooltip>, but here the annotated elements can be nested. The most deeply nested tooltip is shown.
9+
Це як задача <info:task/behavior-tooltip>, але тут елементи можуть бути вкладеними. Ви маєте показати найбільш глибоко вкладену підказку.
1010

11-
Only one tooltip may show up at the same time.
11+
Одночасно може відображатися лише одна підказка.
1212

13-
For instance:
13+
Наприклад:
1414

1515
```html
16-
<div data-tooltip="Hereis the house interior" id="house">
17-
<div data-tooltip="Hereis the roof" id="roof"></div>
16+
<div data-tooltip="Осьінтер’єр будинку" id="house">
17+
<div data-tooltip="Осьдах" id="roof"></div>
1818
...
19-
<a href="https://en.wikipedia.org/wiki/The_Three_Little_Pigs" data-tooltip="Read on">Hover over me</a>
19+
<a href="https://uk.wikipedia.org/wiki/Троє_поросят" data-tooltip="Читайте далі">Наведіть на мене вказівник</a>
2020
</div>
2121
```
2222

23-
The result in iframe:
23+
Результат в iframe:
2424

2525
[iframe src="solution" height=300 border=1]
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`, щоб перевірити, чи підказка працює правильно.

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

+13-13
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;

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

+9-9
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
}

0 commit comments

Comments
 (0)