You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How do we find the width and height of the browser window? How do we get the full width and height of the document, including the scrolled out part? How do we scroll the page using JavaScript?
3
+
Як визначити ширину та висоту вікна браузера? Як отримати повну ширину та висоту документа, включаючи прокручену частину? Як можна прокрутити сторінку за допомогою JavaScript?
4
4
5
-
For this type of information, we can use the root document element `document.documentElement`, that corresponds to the `<html>` tag. But there are additional methods and peculiarities to consider.
5
+
Для цього ми можемо використовувати кореневий елемент документа `document.documentElement`, який відповідає тегу `<html>`. Але є додаткові методи та особливості, які слід враховувати.
6
6
7
-
## Width/height of the window
7
+
## Ширина/висота вікна
8
8
9
-
To get window width and height, we can use the `clientWidth/clientHeight`of`document.documentElement`:
9
+
Щоб отримати ширину та висоту вікна, ми можемо використовувати `clientWidth/clientHeight`із`document.documentElement`:
10
10
11
11

12
12
13
13
```online
14
-
For instance, this button shows the height of your window:
Браузери також підтримують властивості `window.innerWidth/innerHeight`. Здається, це те, що нам потрібно, то чому б їх не використати?
21
21
22
-
If there exists a scrollbar, and it occupies some space, `clientWidth/clientHeight`provide the width/height without it (subtract it). In other words, they return the width/height of the visible part of the document, available for the content.
22
+
Якщо є смуга прокрутки, і вона займає деякий простір, то властивості `clientWidth/clientHeight`нададуть ширину/висоту без прокрутки (віднявши її). Інакше кажучи, вони повертають ширину/висоту видимої частини документа, доступної для вмісту.
23
23
24
-
`window.innerWidth/innerHeight`includes the scrollbar.
In most cases, we need the *available* window width in order to draw or position something within scrollbars (if there are any), so we should use`documentElement.clientHeight/clientWidth`.
32
+
У більшості випадків нам потрібна *доступна* ширина вікна, щоб намалювати або розташувати щось у межах смуг прокрутки (якщо такі є), тому ми повинні використовувати`documentElement.clientHeight/clientWidth`.
33
33
````
34
34
35
-
```warn header="`DOCTYPE` is important"
36
-
Please note: top-level geometry properties may work a little bit differently when there's no `<!DOCTYPE HTML>` in HTML. Odd things are possible.
35
+
```warn header="`DOCTYPE` важливий"
36
+
Зверніть увагу: геометричні властивості верхнього рівня можуть працювати дещо інакше, якщо в HTML немає `<!DOCTYPE HTML>`. Можливі дивні речі.
37
37
38
-
In modern HTML we should always write `DOCTYPE`.
38
+
У сучасному HTML ми завжди повинні прописувати `DOCTYPE`.
39
39
```
40
40
41
-
## Width/height of the document
41
+
## Ширина/висота документа
42
42
43
-
Theoretically, as the root document element is `document.documentElement`, and it encloses all the content, we could measure the document's full size as `document.documentElement.scrollWidth/scrollHeight`.
43
+
Теоретично, оскільки кореневим елементом документа є `document.documentElement`, і він охоплює весь вміст, ми можемо виміряти повний розмір документа як `document.documentElement.scrollWidth/scrollHeight`.
44
44
45
-
But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera, if there's no scroll, then `documentElement.scrollHeight` may be even less than `documentElement.clientHeight`! Weird, right?
45
+
Але для цього елемента для всієї сторінки ці властивості не працюють належним чином. У Chrome/Safari/Opera, якщо немає прокрутки, то `documentElement.scrollHeight` може бути навіть меншим, ніж `documentElement.clientHeight`! Дивно, правда?
46
46
47
-
To reliably obtain the full document height, we should take the maximum of these properties:
47
+
Щоб надійно отримати повну висоту документа, ми повинні взяти максимум з цих властивостей:
48
48
49
49
```js run
50
50
let scrollHeight = Math.max(
@@ -53,110 +53,110 @@ let scrollHeight = Math.max(
alert('Full document height, with scrolled out part: ' + scrollHeight);
56
+
alert('Повна висота документа з прокрученою частиною: ' + scrollHeight);
57
57
```
58
58
59
-
Why so? Better don't ask. These inconsistencies come from ancient times, not a "smart" logic.
59
+
Чому так? Краще не питати. Ці невідповідності походять із давніх часів, це не "логічно".
60
60
61
-
## Get the current scroll [#page-scroll]
61
+
## Отримання поточної позиції прокрутки [#page-scroll]
62
62
63
-
DOM elements have their current scroll state in their `scrollLeft/scrollTop` properties.
63
+
Елементи DOM містять свій поточний стан прокрутки у властивостях `scrollLeft/scrollTop`.
64
64
65
-
For document scroll, `document.documentElement.scrollLeft/scrollTop` works in most browsers, except older WebKit-based ones, like Safari (bug [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), where we should use `document.body` instead of `document.documentElement`.
65
+
Стан прокрутки документа міститься в `document.documentElement.scrollLeft/scrollTop`, та працює в більшості браузерів, за винятком старіших веб-переглядачів створених на WebKit, таких як Safari (помилка [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), де ми повинні використовувати `document.body` замість `document.documentElement`.
66
66
67
-
Luckily, we don't have to remember these peculiarities at all, because the scroll is available in the special properties, `window.pageXOffset/pageYOffset`:
67
+
На щастя, нам не потрібно пам’ятати про ці особливості, оскільки прокрутка доступна у спеціальних властивостях `window.pageXOffset/pageYOffset`:
68
68
69
69
```js run
70
-
alert('Current scroll from the top: ' + window.pageYOffset);
71
-
alert('Current scroll from the left: ' + window.pageXOffset);
To scroll the page with JavaScript, its DOM must be fully built.
85
+
Щоб прокручувати сторінку за допомогою JavaScript, її DOM має бути повністю створено.
86
86
87
-
For instance, if we try to scroll the page with a script in `<head>`, it won't work.
87
+
Наприклад, якщо ми спробуємо прокрутити сторінку за допомогою сценарію в `<head>`, це не спрацює.
88
88
```
89
89
90
-
Regular elements can be scrolled by changing `scrollTop/scrollLeft`.
90
+
Звичайні елементи можна прокручувати, змінюючи `scrollTop/scrollLeft`.
91
91
92
-
We can do the same for the page using `document.documentElement.scrollTop/scrollLeft` (except Safari, where `document.body.scrollTop/Left` should be used instead).
92
+
Ми можемо зробити те ж саме для сторінки, використовуючи `document.documentElement.scrollTop/scrollLeft` (крім Safari, де замість цього слід використовувати `document.body.scrollTop/Left`).
93
93
94
-
Alternatively, there's a simpler, universal solution: special methods [window.scrollBy(x,y)](mdn:api/Window/scrollBy) and [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo).
94
+
Крім того, є більш просте та універсальне рішення: спеціальні методи [window.scrollBy(x,y)](mdn:api/Window/scrollBy) і [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo).
95
95
96
-
- The method `scrollBy(x,y)` scrolls the page *relative to its current position*. For instance, `scrollBy(0,10)` scrolls the page `10px` down.
96
+
- Метод `scrollBy(x,y)` прокручує сторінку *відносно її поточної позиції*. Наприклад, `scrollBy(0,10)` прокручує сторінку на `10px` вниз.
- The method `scrollTo(pageX,pageY)` scrolls the page *to absolute coordinates*, so that the top-left corner of the visible part has coordinates `(pageX, pageY)` relative to the document's top-left corner. It's like setting `scrollLeft/scrollTop`.
103
+
- Метод `scrollTo(pageX,pageY)` прокручує сторінку *до абсолютних координат*, так що верхній лівий кут видимої частини має координати `(pageX, pageY)` відносно верхнього лівого кута документа. Це те ж саме, що призначити `scrollLeft/scrollTop`.
104
104
105
-
To scroll to the very beginning, we can use `scrollTo(0,0)`.
105
+
Щоб прокрутити до самого початку, ми можемо використовувати `scrollTo(0,0)`.
For completeness, let's cover one more method: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
115
+
Для повноти розглянемо ще один метод: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
116
116
117
-
The call to `elem.scrollIntoView(top)` scrolls the page to make `elem` visible. It has one argument:
117
+
Виклик `elem.scrollIntoView(top)` прокручує сторінку таким чином, щоб зробити `elem` видимим. Він має один аргумент:
118
118
119
-
- If `top=true` (that's the default), then the page will be scrolled to make `elem` appear on the top of the window. The upper edge of the element will be aligned with the window top.
120
-
- If `top=false`, then the page scrolls to make `elem` appear at the bottom. The bottom edge of the element will be aligned with the window bottom.
119
+
- Якщо `top=true` (це значення за замовчуванням), то сторінка буде прокручена, щоб `elem` з'явився у верхній частині вікна. Верхній край елемента буде вирівняний з верхньою частиною вікна.
120
+
- Якщо `top=false`, то сторінка прокручується, щоб `elem` з'явився внизу. Нижній край елемента буде вирівняний з нижньою частиною вікна.
121
121
122
122
```online
123
-
The button below scrolls the page to position itself at the window top:
123
+
Кнопка нижче прокручує сторінку, щоб розмістити себе у верхній частині вікна:
Sometimes we need to make the document "unscrollable". For instance, when we need to cover the page with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document.
134
+
Іноді нам потрібно зробити документ «непрокручуваним». Наприклад, коли нам потрібно закрити сторінку великим повідомленням, яке вимагає негайної уваги, і ми хочемо, щоб відвідувач взаємодіяв з цим повідомленням, а не з документом.
135
135
136
-
To make the document unscrollable, it's enough to set `document.body.style.overflow = "hidden"`. The page will "freeze" at its current scroll position.
136
+
Щоб зробити документ недоступним для прокручування, достатньо встановити `document.body.style.overflow = "hidden"`. Сторінка «завмере» у поточній позиції прокручування.
The first button freezes the scroll, while the second one releases it.
145
+
Перша кнопка зупиняє прокрутку, а друга відновлює.
146
146
```
147
147
148
-
We can use the same technique to freeze the scroll for other elements, not just for `document.body`.
148
+
Ми можемо використовувати ту саму техніку, щоб заморозити прокрутку для інших елементів, а не лише для `document.body`.
149
149
150
-
The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free and the content "jumps" to fill it.
150
+
Недоліком цього методу є те, що смуга прокрутки зникає. Якщо вона займала деякий простір, то це місце звільняється, і вміст «стрибає», щоб заповнити його.
151
151
152
-
That looks a bit odd, but can be worked around if we compare `clientWidth` before and after the freeze. If it increased (the scrollbar disappeared), then add `padding` to `document.body` in place of the scrollbar to keep the content width the same.
152
+
Це виглядає трохи дивно, але це можна обійти, якщо порівняти `clientWidth` до і після заборони прокручування. Якщо ширина збільшилась (смуга прокрутки зникла), додайте `padding` до `document.body` замість смуги прокрутки, щоб зберегти ширину вмісту такою ж.
153
153
154
-
## Summary
154
+
## Підсумки
155
155
156
-
Geometry:
156
+
Геометрія:
157
157
158
-
- Width/height of the visible part of the document (content area width/height): `document.documentElement.clientWidth/clientHeight`
159
-
- Width/height of the whole document, with the scrolled out part:
158
+
- Ширина/висота видимої частини документа (ширина/висота області вмісту): `document.documentElement.clientWidth/clientHeight`
159
+
- Ширина/висота всього документа з прокрученою частиною:
160
160
161
161
```js
162
162
let scrollHeight = Math.max(
@@ -166,11 +166,11 @@ Geometry:
166
166
);
167
167
```
168
168
169
-
Scrolling:
169
+
Прокрутка:
170
170
171
-
- Read the current scroll: `window.pageYOffset/pageXOffset`.
0 commit comments