Skip to content

Scrolling #295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Jan 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
c27d035
onscroll
OlhaBrozhenets Jan 26, 2022
aba0b5d
edits onscroll
OlhaBrozhenets Jan 26, 2022
dfdfbec
Update 2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
MykolaSopiha Jan 29, 2022
11c1d61
Update 2-ui/3-event-details/8-onscroll/1-endless-page/source.view/ind…
MykolaSopiha Jan 29, 2022
8c1c4b6
Update 2-ui/3-event-details/8-onscroll/2-updown-button/source.view/in…
MykolaSopiha Jan 29, 2022
b608408
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
34f71ab
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
2a84969
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
7924f06
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
bb68410
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
19155d9
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
7747fa5
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
e7d41dd
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
bb967f1
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
280e2e1
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
1302439
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
d13a378
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
c6c885d
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
c947d65
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
9337c48
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.vi…
MykolaSopiha Jan 29, 2022
90dd61c
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
MykolaSopiha Jan 29, 2022
445fa59
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
MykolaSopiha Jan 29, 2022
543c77e
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
be8bc39
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
c8bf30c
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
33c252a
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/source.view…
MykolaSopiha Jan 29, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 24 additions & 24 deletions 2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,64 @@
The core of the solution is a function that adds more dates to the page (or loads more stuff in real-life) while we're at the page end.
Основою рішення є функція, яка додає більше дат на сторінку (або завантажує більше речей у реальному житті), поки ми знаходимося в кінці сторінки.

We can call it immediately and add as a `window.onscroll` handler.
Ми можемо негайно викликати її та додати `window.onscroll` як обробник.

The most important question is: "How do we detect that the page is scrolled to bottom?"
Найважливіше запитання: "Як ми виявимо, що сторінка прокручується вниз?"

Let's use window-relative coordinates.
Скористаємось координатами, відносними до вікна.

The document is represented (and contained) within `<html>` tag, that is `document.documentElement`.
Документ представлений (і міститься) у тегу `<html>`, тобто `document.documentElement`.

We can get window-relative coordinates of the whole document as `document.documentElement.getBoundingClientRect()`, the `bottom` property will be window-relative coordinate of the document bottom.
Ми можемо отримати відносні до вікна координати всього документа як `document.documentElement.getBoundingClientRect()`, властивість `bottom` буде відносною до вікна координатою низа документа.

For instance, if the height of the whole HTML document is `2000px`, then:
Наприклад, якщо висота всього HTML-документа дорівнює `2000px`, тоді:

```js
// when we're on the top of the page
// window-relative top = 0
// коли ми знаходимося вгорі сторінки
// top відносний до вікна дорівнює 0
document.documentElement.getBoundingClientRect().top = 0

// window-relative bottom = 2000
// the document is long, so that is probably far beyond the window bottom
// bottom відносний до вікна дорівнює 2000
// документ великий, тому він, ймовірно, знаходиться далеко за нижньою частиною вікна
document.documentElement.getBoundingClientRect().bottom = 2000
```

If we scroll `500px` below, then:
Якщо ми прокрутимо `500px` нижче, то:

```js
// document top is above the window 500px
// Верхня частина документа знаходиться над вікном на 500px
document.documentElement.getBoundingClientRect().top = -500
// document bottom is 500px closer
// Нижня частина документа на 500px ближче
document.documentElement.getBoundingClientRect().bottom = 1500
```

When we scroll till the end, assuming that the window height is `600px`:
Коли ми прокручуємо до кінця, припускаючи, що висота вікна дорівнює `600px`:


```js
// document top is above the window 1400px
// Верхня частина документа знаходиться над вікном на 1400px
document.documentElement.getBoundingClientRect().top = -1400
// document bottom is below the window 600px
// Нижня частина документа знаходиться під вікном на 600px
document.documentElement.getBoundingClientRect().bottom = 600
```

Please note that the `bottom` can't be `0`, because it never reaches the window top. The lowest limit of the `bottom` coordinate is the window height (we assumed it to be `600`), we can't scroll it any more up.
Зауважте, що `bottom` не може бути `0`, оскільки він ніколи не досягає верхньої частини вікна. Найнижча межа `bottom` координати -- це висота вікна (ми припустили, що це `600`), ми більше не можемо прокручувати вгору.

We can obtain the window height as `document.documentElement.clientHeight`.
Ми можемо отримати висоту вікна як `document.documentElement.clientHeight`.

For our task, we need to know when the document bottom is not no more than `100px` away from it (that is: `600-700px`, if the height is `600`).
Для нашого завдання нам потрібно знати, коли нижня частина документа знаходиться на відстані не більше ніж `100px` від неї (тобто: `600-700px`, якщо висота `600`).

So here's the function:
Отже, ось функція:

```js
function populate() {
while(true) {
// document bottom
// нижня частина документа
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;

// if the user hasn't scrolled far enough (>100px to the end)
// якщо користувач не прокрутив достатньо далеко (>100px до кінця)
if (windowRelativeBottom > document.documentElement.clientHeight + 100) break;

// let's add more data
// додамо більше даних
document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<body>

<h1>Scroll me</h1>
<h1>Прокрути мене</h1>

<script>
function populate() {
Expand All @@ -19,7 +19,7 @@ <h1>Scroll me</h1>

window.addEventListener('scroll', populate);

populate(); // init document
populate(); // ініціалізація документа
</script>

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<h1>Scroll me</h1>

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

</body>
Expand Down
16 changes: 8 additions & 8 deletions 2-ui/3-event-details/8-onscroll/1-endless-page/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ importance: 5

---

# Endless page
# Нескінченна сторінка

Create an endless page. When a visitor scrolls it to the end, it auto-appends current date-time to the text (so that a visitor can scroll more).
Створіть нескінченну сторінку. Коли відвідувач прокручує її до кінця, поточна дата-час автоматично додається до тексту (щоб відвідувач міг прокручувати більше).

Like this:
ось таким чином:

[iframe src="solution" height=200]

Please note two important features of the scroll:
Будь ласка, зверніть увагу на дві важливі особливості прокрутки:

1. **The scroll is "elastic".** We can scroll a little beyond the document start or end in some browsers/devices (empty space below is shown, and then the document will automatically "bounces back" to normal).
2. **The scroll is imprecise.** When we scroll to page end, then we may be in fact like 0-50px away from the real document bottom.
1. **Прокручування є "еластичним".** У деяких браузерах/пристроях ми можемо прокрутити трохи далі початку або кінця документа (буде показано пусте місце, а потім документ автоматично "повернеться" до нормального стану).
2. **Прокрутка неточна.** Коли ми прокручуємо до кінця сторінки, насправді ми можемо бути на відстані 0-50 пікселів від реального низу документа.

So, "scrolling to the end" should mean that the visitor is no more than 100px away from the document end.
Отже, "прокрутка до кінця" має означати, що відвідувач знаходиться на відстані не більше 100 пікселів від кінця документа.

P.S. In real life we may want to show "more messages" or "more goods".
P.S. У реальному житті ми можемо захотіти показати "більше повідомлень" або "більше товарів".
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@

arrowTop.onclick = function() {
window.scrollTo(pageXOffset, 0);
// after scrollTo, there will be a "scroll" event, so the arrow will hide automatically
// після scrollTo відбудеться подія "scroll", тому стрілка автоматично сховається
};

window.addEventListener('scroll', function() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<div id="arrowTop"></div>

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

</body>
Expand Down
14 changes: 7 additions & 7 deletions 2-ui/3-event-details/8-onscroll/2-updown-button/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ importance: 5

---

# Up/down button
# Кнопка вгору/вниз

Create a "to the top" button to help with page scrolling.
Створіть кнопку "вгору", щоб допомогти прокручувати сторінку.

It should work like this:
- While the page is not scrolled down at least for the window height -- it's invisible.
- When the page is scrolled down more than the window height -- there appears an "upwards" arrow in the left-top corner. If the page is scrolled back, it disappears.
- When the arrow is clicked, the page scrolls to the top.
Вона має працювати так:
- Поки сторінка не прокручена принаймні на висоту вікна -- вона невидима.
- Якщо сторінка прокручена нижче висоти вікна, у верхньому лівому куті з’являється стрілка "вгору". Якщо сторінку прокрутити назад, вона зникне.
- При натисканні стрілки сторінка прокручується вгору.

Like this (top-left corner, scroll to see):
Ось так (верхній лівий кут, прокрутіть, щоб побачити):

[iframe border="1" height="200" link src="solution"]
18 changes: 9 additions & 9 deletions 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
The `onscroll` handler should check which images are visible and show them.
Обробник `onscroll` повинен перевірити, які зображення є видимими, і показати їх.

We also want to run it when the page loads, to detect immediately visible images and load them.
Ми також хочемо запускати його під час завантаження сторінки, щоб виявляти видимі зображення відразу та завантажувати їх.

The code should execute when the document is loaded, so that it has access to its content.
Код повинен виконуватися під час завантаження документа, щоб він мав доступ до його вмісту.

Or put it at the `<body>` bottom:
Або розмістіть його внизу `<body>`:

```js
// ...the page content is above...
// ...вміст сторінки вище...

function isVisible(elem) {

let coords = elem.getBoundingClientRect();

let windowHeight = document.documentElement.clientHeight;

// top elem edge is visible?
// видно верхній край елемента?
let topVisible = coords.top > 0 && coords.top < windowHeight;

// bottom elem edge is visible?
// видно нижній край елемента?
let bottomVisible = coords.bottom < windowHeight && coords.bottom > 0;

return topVisible || bottomVisible;
}
```

The `showVisible()` function uses the visibility check, implemented by `isVisible()`, to load visible images:
Функція `showVisible()` використовує перевірку видимості, реалізовану `isVisible()`, для завантаження видимих зображень:

```js
function showVisible() {
Expand All @@ -46,4 +46,4 @@ window.onscroll = showVisible;
*/!*
```

P.S. The solution also has a variant of `isVisible` that "preloads" images that are within 1 page above/below the current document scroll.
P.S. Рішення також має варіант `isVisible`, який "попередньо завантажує" зображення, які знаходяться в межах 1 сторінки вище/під поточною прокруткою документа.
Loading