diff --git a/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.md b/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.md index 4101d4915..8a7de1772 100644 --- a/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.md +++ b/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.md @@ -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(); @@ -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 = [ @@ -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 = [ diff --git a/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.view/index.html b/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.view/index.html index 229c87186..3cd2e0a4c 100755 --- a/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.view/index.html +++ b/2-ui/1-document/11-coordinates/1-find-point-coordinates/solution.view/index.html @@ -5,7 +5,7 @@ @@ -13,10 +13,10 @@ - Click anywhere to get window coordinates. -
That's for testing, to check the result you get by JavaScript. + Клацніть будь-де, щоб отримати координати вікна. +
Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
-
(click coordinates show up here)
+
(координати кліку з’являться тут)
diff --git a/2-ui/1-document/11-coordinates/1-find-point-coordinates/source.view/index.html b/2-ui/1-document/11-coordinates/1-find-point-coordinates/source.view/index.html index dd168f783..c14317c2c 100755 --- a/2-ui/1-document/11-coordinates/1-find-point-coordinates/source.view/index.html +++ b/2-ui/1-document/11-coordinates/1-find-point-coordinates/source.view/index.html @@ -5,7 +5,7 @@ @@ -13,10 +13,10 @@ - Click anywhere to get window coordinates. -
That's for testing, to check the result you get by JavaScript. + Клацніть будь-де, щоб отримати координати вікна. +
Це для тестування, щоб перевірити результат, який ви отримуєте за допомогою JavaScript.
-
(click coordinates show up here)
+
(координати кліку з’являться тут)
@@ -32,7 +32,7 @@ diff --git a/2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md b/2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md index 6bbb9fe13..049eac3d1 100644 --- a/2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md +++ b/2-ui/1-document/11-coordinates/1-find-point-coordinates/task.md @@ -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. Код також повинен працювати, якщо елемент має інший розмір або рамку, тобто не прив’язаний до жодних фіксованих значень. diff --git a/2-ui/1-document/11-coordinates/2-position-at/solution.md b/2-ui/1-document/11-coordinates/2-position-at/solution.md index 353eb65dd..4fd4dee6e 100644 --- a/2-ui/1-document/11-coordinates/2-position-at/solution.md +++ b/2-ui/1-document/11-coordinates/2-position-at/solution.md @@ -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`) або елемент поза документом не має розміру. diff --git a/2-ui/1-document/11-coordinates/2-position-at/solution.view/index.html b/2-ui/1-document/11-coordinates/2-position-at/solution.view/index.html index f931fbeac..ddfdeac03 100755 --- a/2-ui/1-document/11-coordinates/2-position-at/solution.view/index.html +++ b/2-ui/1-document/11-coordinates/2-position-at/solution.view/index.html @@ -12,10 +12,10 @@ esse sequi officia sapiente.

- 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. + Учитель: Чому ти спізнився? + Учень: Зустрів чоловіка, який загубив стодоларову купюру. + Учитель: Отакої. Ти допомагав йому шукати? + Учень: Ні, я стояв на ній.

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 @@ -24,13 +24,13 @@ -If you scroll the page and repeat, you'll notice that as window-relative button position changes, its window coordinates (`y/top/bottom` if you scroll vertically) change as well. +Якщо ви прокрутите сторінку та спробуєте знову, то помітите, що по мірі зміни положення кнопки, змінюються і ЇЇ координати відносно вікна (`y/top/bottom`, при вертикальній прокрутці). ``` -Here's the picture of `elem.getBoundingClientRect()` output: +Ось зображення з результатом виклику `elem.getBoundingClientRect()`: ![](coordinates.svg) -As you can see, `x/y` and `width/height` fully describe the rectangle. Derived properties can be easily calculated from them: +Як бачите, `x/y` та `width/height` повністю описують прямокутник. З них можна легко обчислити похідні властивості: - `left = x` - `top = y` - `right = x + width` - `bottom = y + height` -Please note: +Зверніть увагу: -- Coordinates may be decimal fractions, such as `10.5`. That's normal, internally browser uses fractions in calculations. We don't have to round them when setting to `style.left/top`. -- Coordinates may be negative. For instance, if the page is scrolled so that `elem` is now above the window, then `elem.getBoundingClientRect().top` is negative. +- Координати можуть бути десятковими дробами, наприклад `10.5`. Це нормально, тому, що внутрішньо браузер використовує дроби у своїх обчисленнях. Нам не потрібно їх округлювати, коли встановлюємо значення `style.left/top`. +– Координати можуть бути від’ємними. Наприклад, якщо сторінка прокручена таким чином, що `elem` знаходиться над видимою частиною вікна, то `elem.getBoundingClientRect().top` буде від’ємними. -```smart header="Why derived properties are needed? Why does `top/left` exist if there's `x/y`?" -Mathematically, a rectangle is uniquely defined with its starting point `(x,y)` and the direction vector `(width,height)`. So the additional derived properties are for convenience. +```smart header="Навіщо потрібні похідні властивості? Чому існує `top/left`, якщо є `x/y`?" +Математично прямокутник однозначно визначається його початковою точкою `(x,y)` і вектором напрямку `(width,height)`. Тому додаткові похідні властивості призначені для зручності. -Technically it's possible for `width/height` to be negative, that allows for "directed" rectangle, e.g. to represent mouse selection with properly marked start and end. +Технічно можливо, щоб `width/height` були від’ємними, це дозволяє використовувати «спрямований» прямокутник, наприклад для представлення виділення мишею з правильно позначеними початком і кінцем. -Negative `width/height` values mean that the rectangle starts at its bottom-right corner and then "grows" left-upwards. +Від’ємні значення `width/height` означають, що прямокутник починається з нижнього правого кута, а потім "зростає" ліворуч вгору. -Here's a rectangle with negative `width` and `height` (e.g. `width=-200`, `height=-100`): +Ось прямокутник із від’ємними значеннями `width` і `height` (наприклад, `width=-200`, `height=-100`): ![](coordinates-negative.svg) -As you can see, `left/top` do not equal `x/y` in such case. +Як бачите, у такому випадку, `left/top` не дорівнює `x/y`. -In practice though, `elem.getBoundingClientRect()` always returns positive width/height, here we mention negative `width/height` only for you to understand why these seemingly duplicate properties are not actually duplicates. +Однак на практиці `elem.getBoundingClientRect()` завжди повертає позитивні значення ширини/висоти, тут ми згадуємо про негативні значення `width/height` лише для того, щоб ви зрозуміли, чому ці, здавалося б, повторювані властивості насправді не є повторюваними. ``` -```warn header="Internet Explorer: no support for `x/y`" -Internet Explorer doesn't support `x/y` properties for historical reasons. +```warn header="Internet Explorer: немає підтримки `x/y`" +Internet Explorer не підтримує властивості `x/y` з історичних причин. -So we can either make a polyfill (add getters in `DomRect.prototype`) or just use `top/left`, as they are always the same as `x/y` for positive `width/height`, in particular in the result of `elem.getBoundingClientRect()`. +Тож ми можемо або створити поліфіл (додати гетери в `DomRect.prototype`), або просто використовувати `top/left`, оскільки вони завжди дорівнюють `x/y` для додатніх `width/height`, зокрема в результаті виклику `elem.getBoundingClientRect()`. ``` -```warn header="Coordinates right/bottom are different from CSS position properties" -There are obvious similarities between window-relative coordinates and CSS `position:fixed`. +```warn header="Координати right/bottom відрізняються від однойменних властивостей CSS" +Існує очевидна подібність між координатами відносними до вікна, та CSS `position:fixed`. -But in CSS positioning, `right` property means the distance from the right edge, and `bottom` property means the distance from the bottom edge. +Але в CSS властивість `right` означає відстань від правого краю, а властивість `bottom` означає відстань від нижнього краю. -If we just look at the picture above, we can see that in JavaScript it is not so. All window coordinates are counted from the top-left corner, including these ones. +Якщо подивимося на малюнок вище, то побачимо, що в JavaScript це не так. Усі координати вікна відраховуються від верхнього лівого кута, включаючи `right` та `bottom`. ``` ## elementFromPoint(x, y) [#elementFromPoint] -The call to `document.elementFromPoint(x, y)` returns the most nested element at window coordinates `(x, y)`. +Виклик `document.elementFromPoint(x, y)` повертає найбільш вкладений елемент вікна з координатами `(x, y)`. -The syntax is: +Синтаксис такий: ```js let elem = document.elementFromPoint(x, y); ``` -For instance, the code below highlights and outputs the tag of the element that is now in the middle of the window: +Наприклад, наведений нижче код виділяє та виводить тег елемента, який зараз знаходиться в середині вікна: ```js run let centerX = document.documentElement.clientWidth / 2; @@ -124,43 +124,43 @@ elem.style.background = "red"; alert(elem.tagName); ``` -As it uses window coordinates, the element may be different depending on the current scroll position. +Оскільки код використовує координати відносно вікна, то елемент може відрізнятися залежно від поточної позиції прокручування. -````warn header="For out-of-window coordinates the `elementFromPoint` returns `null`" -The method `document.elementFromPoint(x,y)` only works if `(x,y)` are inside the visible area. +````warn header="Для координат, які знаходяться поза вікном `elementFromPoint` повертає `null`" +Метод `document.elementFromPoint(x,y)` працює, лише якщо координати `(x,y)` знаходяться у видимій області вікна. -If any of the coordinates is negative or exceeds the window width/height, then it returns `null`. +Якщо будь-яка з координат від’ємна, або більша ніж ширина/висота вікна, то повертається `null`. -Here's a typical error that may occur if we don't check for it: +Ось типова помилка, яка може виникнути, якщо не додати перевірку: ```js let elem = document.elementFromPoint(x, y); -// if the coordinates happen to be out of the window, then elem = null +// якщо координати виходять за межі вікна, то elem = null *!* -elem.style.background = ''; // Error! +elem.style.background = ''; // Помилка! */!* ``` ```` -## Using for "fixed" positioning +## Використання разом з "position:fixed" -Most of time we need coordinates in order to position something. +Найчастіше нам потрібні координати, щоб щось розташувати. -To show something near an element, we can use `getBoundingClientRect` to get its coordinates, and then CSS `position` together with `left/top` (or `right/bottom`). +Щоб показати щось поблизу елемента, ми можемо використати `getBoundingClientRect` для отримання його координат, а потім CSS `position` разом із `left/top` (або `right/bottom`). -For instance, the function `createMessageUnder(elem, html)` below shows the message under `elem`: +Наприклад, наведена нижче функція `createMessageUnder(elem, html)` виводить повідомлення під елементом `elem`: ```js let elem = document.getElementById("coords-show-mark"); function createMessageUnder(elem, html) { - // create message element + // створюємо елемент повідомлення let message = document.createElement('div'); - // better to use a css class for the style here + // тут краще було б використати CSS клас message.style.cssText = "position:fixed; color: red"; *!* - // assign coordinates, don't forget "px"! + // призначаємо координати, не забуваємо про "px"! let coords = elem.getBoundingClientRect(); message.style.left = coords.left + "px"; @@ -172,45 +172,45 @@ function createMessageUnder(elem, html) { return message; } -// Usage: -// add it for 5 seconds in the document -let message = createMessageUnder(elem, 'Hello, world!'); +// Використання: +// додаємо повідомлення у документ на 5 секунд +let message = createMessageUnder(elem, 'Привіт, світ!'); document.body.append(message); setTimeout(() => message.remove(), 5000); ``` ```online -Click the button to run it: +Натисніть кнопку, щоб запустити приклад: - + ``` -The code can be modified to show the message at the left, right, below, apply CSS animations to "fade it in" and so on. That's easy, as we have all the coordinates and sizes of the element. +Код можна змінити, щоб показати повідомлення ліворуч, праворуч, знизу, застосувати CSS анімацію, і так далі. Це легко, оскільки у нас є всі координати та розміри елемента. -But note the important detail: when the page is scrolled, the message flows away from the button. +Але зверніть увагу на важливу деталь: коли сторінка прокручується, повідомлення відпливає від кнопки. -The reason is obvious: the message element relies on `position:fixed`, so it remains at the same place of the window while the page scrolls away. +Причина очевидна: елемент повідомлення позиціонується за допомогою `position:fixed`, тому він залишається на тому ж місці у вікні, під час прокрутки сторінки. -To change that, we need to use document-based coordinates and `position:absolute`. +Щоб це змінити, нам потрібно використовувати систему координат відносно документа та `position:absolute`. -## Document coordinates [#getCoords] +## Координати відносно документа [#getCoords] -Document-relative coordinates start from the upper-left corner of the document, not the window. +Координати, відносні до документа, починаються з верхнього лівого кута документа, а не вікна. -In CSS, window coordinates correspond to `position:fixed`, while document coordinates are similar to `position:absolute` on top. +У CSS координати відносно вікна відповідають `position:fixed`, тоді як координати відносно документа подібні до `position:absolute` на верхньому рівні вкладеності. -We can use `position:absolute` and `top/left` to put something at a certain place of the document, so that it remains there during a page scroll. But we need the right coordinates first. +Ми можемо використовувати `position:absolute` і `top/left`, щоб розмістити щось у певному місці документа таким чином, щоб воно залишалося там навіть під час прокручування сторінки. Але спочатку нам потрібно отримати правильні координати. -There's no standard method to get the document coordinates of an element. But it's easy to write it. +Не існує стандартного методу для отримання координат елемента відносно до документа. Але написати його легко. -The two coordinate systems are connected by the formula: -- `pageY` = `clientY` + height of the scrolled-out vertical part of the document. -- `pageX` = `clientX` + width of the scrolled-out horizontal part of the document. +Дві системи координат з’єднуються за формулою: +- `pageY` = `clientY` + висота прокрученої вертикальної частини документа. +- `pageX` = `clientX` + ширина прокрученої горизонтальної частини документа. -The function `getCoords(elem)` will take window coordinates from `elem.getBoundingClientRect()` and add the current scroll to them: +Функція `getCoords(elem)` візьме координати вікна з `elem.getBoundingClientRect()` і додасть до них значення поточної прокрутки: ```js -// get document coordinates of the element +// отримуємо координати елемента відносно документа function getCoords(elem) { let box = elem.getBoundingClientRect(); @@ -223,9 +223,9 @@ function getCoords(elem) { } ``` -If in the example above we used it with `position:absolute`, then the message would stay near the element on scroll. +Якщо б у наведеному вище прикладі ми використовували його разом з `position:absolute`, то повідомлення залишалося б біля елемента під час прокручування. -The modified `createMessageUnder` function: +Модифікована функція `createMessageUnder`: ```js function createMessageUnder(elem, html) { @@ -243,13 +243,13 @@ function createMessageUnder(elem, html) { } ``` -## Summary +## Підсумки -Any point on the page has coordinates: +Будь-яка точка на сторінці має координати: -1. Relative to the window -- `elem.getBoundingClientRect()`. -2. Relative to the document -- `elem.getBoundingClientRect()` plus the current page scroll. +1. Відносно вікна -- `elem.getBoundingClientRect()`. +2. Відносно документа -- `elem.getBoundingClientRect()` плюс значення поточної прокрутки. -Window coordinates are great to use with `position:fixed`, and document coordinates do well with `position:absolute`. +Координати відносно вікна зручно використовувати з `position:fixed`, а координати відносно документа з `position:absolute`. -Both coordinate systems have their pros and cons; there are times we need one or the other one, just like CSS `position` `absolute` and `fixed`. +Обидві системи координат мають свої плюси і мінуси. Іноді нам потрібна та чи інша, так само я і в CSS ми обираємо CSS `position` між `absolute` та `fixed`.