Coordinates by jeneg · Pull Request #305 · javascript-tutorial/uk.javascript.info

18 changes: 9 additions & 9 deletions 2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.md

Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Outer corners
# Зовнішні кути

Outer corners are basically what we get from [elem.getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect).
Зовнішні кути -- це саме те, що ми отримуємо в результаті виклику [elem.getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect).

Coordinates of the upper-left corner `answer1` and the bottom-right corner `answer2`:
Координати верхнього лівого кута `answer1` і нижнього правого кута `answer2`:

```js
let coords = elem.getBoundingClientRect();
Expand All @@ -11,19 +11,19 @@ let answer1 = [coords.left, coords.top];
let answer2 = [coords.right, coords.bottom];
```

# Left-upper inner corner
# Лівий верхній внутрішній кут

That differs from the outer corner by the border width. A reliable way to get the distance is `clientLeft/clientTop`:
Координати внутрішнього кута відрізняється від зовнішнього на ширину рамки. Надійним способом їх отримання є використання `clientLeft/clientTop`:

```js
let answer3 = [coords.left + field.clientLeft, coords.top + field.clientTop];
```

# Right-bottom inner corner
# Правий нижній внутрішній кут

In our case we need to substract the border size from the outer coordinates.
У нашому випадку нам потрібно відняти розмір рамки від зовнішніх координат.

We could use CSS way:
Можемо використати CSS властивості:

```js
let answer4 = [
Expand All @@ -32,7 +32,7 @@ let answer4 = [
];
```

An alternative way would be to add `clientWidth/clientHeight` to coordinates of the left-upper corner. That's probably even better:
Альтернативним способом було б додавання `clientWidth/clientHeight` до координат лівого верхнього кута. Це, мабуть, навіть краще:

```js
let answer4 = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<script>
document.onclick = function(e) { // shows click coordinates
document.onclick = function(e) { // показує координати кліку
coords.innerHTML = e.clientX + ':' + e.clientY;
};
</script>
</head>

<body>

Click anywhere to get window coordinates.
<br> That's for testing, to check the result you get by JavaScript.
Клацніть будь-де, щоб отримати координати вікна.
<br> Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
<br>
<div id="coords">(click coordinates show up here)</div>
<div id="coords">(координати кліку з’являться тут)</div>


<div id="field">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<script>
document.onclick = function(e) { // shows click coordinates
document.onclick = function(e) { // показує координати кліку
coords.innerHTML = e.clientX + ':' + e.clientY;
};
</script>
</head>

<body>

Click anywhere to get window coordinates.
<br> That's for testing, to check the result you get by JavaScript.
Клацніть будь-де, щоб отримати координати вікна.
<br> Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
<br>
<div id="coords">(click coordinates show up here)</div>
<div id="coords">(координати кліку з’являться тут)</div>


<div id="field">
Expand All @@ -32,7 +32,7 @@


<script>
// ...your code...
// ...ваш код...
</script>

</body>
Expand Down

24 changes: 12 additions & 12 deletions 2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md

Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
importance: 5
важливість: 5

---

# Find window coordinates of the field
# Знайти координати поля відносно вікна

In the iframe below you can see a document with the green "field".
У iframe нижче ви можете побачити документ із зеленим «полем».

Use JavaScript to find window coordinates of corners pointed by with arrows.
Використовуючи JavaScript, знайдіть координати кутів відносно вікна, на які вказано стрілками.

There's a small feature implemented in the document for convenience. A click at any place shows coordinates there.
Для зручності в документі реалізована невелика функція, яка показує координати кліку.

[iframe border=1 height=360 src="source" link edit]

Your code should use DOM to get window coordinates of:
Ваш код повинен використовувати DOM для отримання чотирьох пар координат відносно вікна:

1. Upper-left, outer corner (that's simple).
2. Bottom-right, outer corner (simple too).
3. Upper-left, inner corner (a bit harder).
4. Bottom-right, inner corner (there are several ways, choose one).
1. Верхній лівий, зовнішній кут (це просто).
2. Правий нижній, зовнішній кут (теж просто).
3. Верхній лівий, внутрішній кут (трохи складніше).
4. Правий нижній, внутрішній кут (є кілька способів, оберіть один).

The coordinates that you calculate should be the same as those returned by the mouse click.
Обчислені координати повинні збігатися з тими, які повертаються клацанням миші.

P.S. The code should also work if the element has another size or border, not bound to any fixed values.
P.S. Код також повинен працювати, якщо елемент має інший розмір або рамку, тобто не прив’язаний до жодних фіксованих значень.

6 changes: 3 additions & 3 deletions 2-ui/1-document/11-coordinates/2-position-at/solution.md

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
In this task we only need to accurately calculate the coordinates. See the code for details.
У цьому завданні нам потрібно лише точно розрахувати координати. Подробиці дивіться в коді.

Please note: the elements must be in the document to read `offsetHeight` and other properties.
A hidden (`display:none`) or out of the document element has no size.
Зверніть увагу: елементи повинні бути в документі, щоб прочитати `offsetHeight` та інші властивості.
Прихований елемент (`display:none`) або елемент поза документом не має розміру.

24 changes: 12 additions & 12 deletions 2-ui/1-document/11-coordinates/2-position-at/solution.view/index.html

Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand All @@ -24,13 +24,13 @@

<script>
/**
* Positions elem relative to anchor as said in position.
* Розміщує елемент elem відносно елемента anchor так, як зазначено в положенні position.
*
* @param {Node} anchor Anchor element for positioning
* @param {string} position One of: top/right/bottom
* @param {Node} elem Element to position
* @param {Node} anchor Елемент, відносно якого позиціонується елемент elem
* @param {string} position Один з: top/right/bottom
* @param {Node} elem Елемент, який позиціонується
*
* Both elements: elem and anchor must be in the document
* Обидва елементи: elem і anchor повинні бути в документі
*/
function positionAt(anchor, position, elem) {

Expand All @@ -56,8 +56,8 @@
}

/**
* Shows a note with the given html at the given position
* relative to the anchor element.
* Показує примітку із заданим HTML у заданій позиції
* відносно елемента anchor.
*/
function showNote(anchor, position, html) {

Expand All @@ -69,7 +69,7 @@
positionAt(anchor, position, note);
}

// test it
// спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down

26 changes: 13 additions & 13 deletions 2-ui/1-document/11-coordinates/2-position-at/source.view/index.html

Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand All @@ -24,21 +24,21 @@

<script>
/**
* Positions elem relative to anchor as said in position.
* Розміщує елемент elem відносно елемента anchor так, як зазначено в положенні position.
*
* @param {Node} anchor Anchor element for positioning
* @param {string} position One of: top/right/bottom
* @param {Node} elem Element to position
* @param {Node} anchor Елемент, відносно якого позиціонується елемент elem
* @param {string} position Один з: top/right/bottom
* @param {Node} elem Елемент, який позиціонується
*
* Both elements: elem and anchor must be in the document
* Обидва елементи: elem і anchor повинні бути в документі
*/
function positionAt(anchor, position, elem) {
// ... your code ...
// ... ваш код ...
}

/**
* Shows a note with the given html at the given position
* relative to the anchor element.
* Показує примітку із заданим HTML у заданій позиції
* відносно елемента anchor.
*/
function showNote(anchor, position, html) {

Expand All @@ -50,7 +50,7 @@
positionAt(anchor, position, note);
}

// test it
// спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down

18 changes: 9 additions & 9 deletions 2-ui/1-document/11-coordinates/2-position-at/task.md

Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
importance: 5
важливість: 5

---

# Show a note near the element
# Покажіть примітку біля елемента

Create a function `positionAt(anchor, position, elem)` that positions `elem`, depending on `position` near `anchor` element.
Створіть функцію `positionAt(anchor, position, elem)`, яка позиціонує `elem` залежно від `position` біля елемента `anchor`.

The `position` must be a string with any one of 3 values:
- `"top"` - position `elem` right above `anchor`
- `"right"` - position `elem` immediately at the right of `anchor`
- `"bottom"` - position `elem` right below `anchor`
Аргумент `position` має бути рядком з будь-яким із 3 значень:
- `"top"` - розмістити `elem` праворуч над `anchor`
- `"right"` - розмістити `elem` безпосередньо праворуч від `anchor`
- `"bottom"` - розмістити `elem` прямо під `anchor`

It's used inside function `showNote(anchor, position, html)`, provided in the task source code, that creates a "note" element with given `html` and shows it at the given `position` near the `anchor`.
Аргумент використовується всередині функції `showNote(anchor, position, html)`, наданої у вихідному коді завдання, який створює елемент примітки із заданим `html` і показує його у заданій позиції `position` біля елементу `anchor`.

Here's the demo of notes:
Ось демонстрація приміток:

[iframe src="solution" height="350" border="1" link]

6 changes: 3 additions & 3 deletions 2-ui/1-document/11-coordinates/3-position-at-absolute/solution.md

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution is actually pretty simple:
Рішення насправді досить просте:

- Use `position:absolute` in CSS instead of `position:fixed` for `.note`.
- Use the function [getCoords()](info:coordinates#getCoords) from the chapter <info:coordinates> to get document-relative coordinates.
- Використовуйте `position:absolute` у CSS замість `position:fixed` для елемента `.note`.
- Використовуйте функцію [getCoords()](info:coordinates#getCoords) з розділу <info:coordinates>, щоб отримати координати відносно документа.
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand Down Expand Up @@ -66,7 +66,7 @@
positionAt(anchor, position, note);
}

// test it
// спробуємо
let blockquote = document.querySelector('blockquote');

showNote(blockquote, "top", "note above");
Expand Down

10 changes: 5 additions & 5 deletions 2-ui/1-document/11-coordinates/3-position-at-absolute/task.md

Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
importance: 5
важливість: 5

---

# Show a note near the element (absolute)
# Покажіть примітку біля елемента (абсолютне позиціювання)

Modify the solution of the [previous task](info:task/position-at) so that the note uses `position:absolute` instead of `position:fixed`.
Скорегуйте рішення [попереднього завдання](info:task/position-at), щоб для позиціювання примітки використовувалася властивість `position:absolute` замість `position:fixed`.

That will prevent its "runaway" from the element when the page scrolls.
Це запобіжить «втечу» нотатки від елемента під час прокручування сторінки.

Take the solution of that task as a starting point. To test the scroll, add the style `<body style="height: 2000px">`.
Візьміть розв’язання попереднього завдання за відправну точку. Щоб перевірити прокрутку, додайте стиль `<body style="height: 2000px">`.
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
esse sequi officia sapiente.</p>

<blockquote>
Teacher: Why are you late?
Student: There was a man who lost a hundred dollar bill.
Teacher: That's nice. Were you helping him look for it?
Student: No. I was standing on it.
Учитель: Чому ти спізнився?
Учень: Зустрів чоловіка, який загубив стодоларову купюру.
Учитель: Отакої. Ти допомагав йому шукати?
Учень: Ні, я стояв на ній.
</blockquote>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit sint atque dolorum fuga ad incidunt voluptatum error fugiat animi amet! Odio temporibus nulla id unde quaerat dignissimos enim nisi rem provident molestias sit tempore omnis recusandae
Expand Down

22 changes: 11 additions & 11 deletions 2-ui/1-document/11-coordinates/4-position-inside-absolute/task.md

Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
importance: 5
важливість: 5

---

# Position the note inside (absolute)
# Розташуйте примітку всередині елемента (абсолютне позиціювання)

Extend the previous task <info:task/position-at-absolute>: teach the function `positionAt(anchor, position, elem)` to insert `elem` inside the `anchor`.
Розширте попереднє завдання <info:task/position-at-absolute>: навчіть функцію `positionAt(anchor, position, elem)` вставляти `elem` всередині `anchor`.

New values for `position`:
Нові значення для `position`:

- `top-out`, `right-out`, `bottom-out` -- work the same as before, they insert the `elem` over/right/under `anchor`.
- `top-in`, `right-in`, `bottom-in` -- insert `elem` inside the `anchor`: stick it to the upper/right/bottom edge.
- `top-out`, `right-out`, `bottom-out` -- працюють так само як і раніше, вони вставляють `elem` над/праворуч/під елементом `anchor`.
- `top-in`, `right-in`, `bottom-in` -- вставляють `elem` всередину елемента `anchor`, та прикріпляють його до верхнього/правого/нижнього краю.

For instance:
Наприклад:

```js
// shows the note above blockquote
// показує примітку над елементом blockquote
positionAt(blockquote, "top-out", note);

// shows the note inside blockquote, at the top
// показує примітку всередині елемента blockquote поряд з верхнім краєм
positionAt(blockquote, "top-in", note);
```

The result:
Результат:

[iframe src="solution" height="310" border="1" link]

As the source code, take the solution of the task <info:task/position-at-absolute>.
Для початку візьміть розв’язання задачі <info:task/position-at-absolute>.