Skip to content

Scrolling #266

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 2 commits into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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.
Il cuore della soluzione è una funzione che aggiunge continuamente contenuti nella pagina (o carica più cose nei casi reali) una volta arrivati alla fine del documento.

We can call it immediately and add as a `window.onscroll` handler.
Possiamo chiamarla subito, ed aggiungerla come gestore di `window.onscroll`.

The most important question is: "How do we detect that the page is scrolled to bottom?"
La domanda fondamentale è: "Come possiamo rilevare che la pagina è arrivata alla fine dello scroll?"

Let's use window-relative coordinates.
Usando le coordinate relative alla finestra.

The document is represented (and contained) within `<html>` tag, that is `document.documentElement`.
Il documento è rappresentato (e contenuto) all'interno del tag `<html>`, che è `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.
Possiamo ottenere le coordinate relative alla finestra dell'intero documento con `document.documentElement.getBoundingClientRect()`, la proprietà `bottom` sarà la coordinata relativa alla finestra, della parte bassa del documento.

For instance, if the height of the whole HTML document is `2000px`, then:
Per esempio, se l'altezza di tutti il documento HTML è `2000px`, allora avremo che:

```js
// when we're on the top of the page
// window-relative top = 0
// quando siamo all'inizio della pagina
// il top rispetto alla finestra = 0
document.documentElement.getBoundingClientRect().top = 0

// window-relative bottom = 2000
// the document is long, so that is probably far beyond the window bottom
// la parte bassa relativa alla finestra = 2000
// il documento è lungo, quindi probabilmente andrà oltre il limite inferiore della finestra
document.documentElement.getBoundingClientRect().bottom = 2000
```

If we scroll `500px` below, then:
Se scrolliamo verso il basso di `500px`, avremo che:

```js
// document top is above the window 500px
// la sommità del documento sta sopra la finestra di 500px
document.documentElement.getBoundingClientRect().top = -500
// document bottom is 500px closer
// la parte bassa del documento, invece, sarà 500px un po' più vicina
document.documentElement.getBoundingClientRect().bottom = 1500
```

When we scroll till the end, assuming that the window height is `600px`:
Quando avremo scrollato la pagina fino alla fine, posto che l'altezza della finestrta sia di `600px`:


```js
// document top is above the window 1400px
// la sommità del documento starà sopra la finestra di 1400px
document.documentElement.getBoundingClientRect().top = -1400
// document bottom is below the window 600px
// la parte bassa del documento sarà più in basso rispetto alla finestra di 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.
Notate bene che `bottom` non può essere `0`, perché non arriva mai all'inizio della finestra. Il limite basso delle coordinate di `bottom` è l'altezza della finestra (stiamo ponendo il caso che questa sia `600`), e non può scrollare più in alto.

We can obtain the window height as `document.documentElement.clientHeight`.
Ricaviamo, quindi, l'altezza della finestra attraverso `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`).
Per i nostri scopi, ci serve sapere momento in cui la fine del documento si troverà a non più di `100px`. (che è a: `600-700px`, se l'altezza è di `600`).

So here's the function:
Ecco quindi la funzione:

```js
function populate() {
while(true) {
// document bottom
// fine del documento
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;

// if the user hasn't scrolled far enough (>100px to the end)
// se l'utente non ha scrollato abbastanza (>100px dalla fine)
if (windowRelativeBottom > document.documentElement.clientHeight + 100) break;

// let's add more data
// aggiungiamo più dati
document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ <h1>Scroll me</h1>

window.addEventListener('scroll', populate);

populate(); // init document
populate(); // init del document
</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 ...
// ... il vostro codice ...
</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
# Pagina senza fine

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).
Create una pagina senza fine. Quando un visitatore scrolla fino alla fine della pagina, la data attuale deve essere accodata (cosicché il visitatore possa scrollare ancora).

Like this:
Come in questo esempio:

[iframe src="solution" height=200]

Please note two important features of the scroll:
È importante notare due caratteristeiche dello 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. **Lo scroll è "elastico".** Possiamo scrollare un po' oltre rispetto all'inizio o alla fine del documento in alcuni browser o dispositivi (verrà mostrato uno spazio vuoto, e subito dopo il documento "rimbalzerà indietro" in posizione normale).
2. **Lo scroll è impreciso.** Quando scrolliamo alla fine della pagina, potrebbe di fatto andare da 0 a 50px fuori dal reale bordo inferiore del documento.

So, "scrolling to the end" should mean that the visitor is no more than 100px away from the document end.
Quindi, "scrollare fino alla fine" dovrebbe significare che il visitatore è a non più di 100px dalla fine del documento.

P.S. In real life we may want to show "more messages" or "more goods".
P.S. Nei casi reali, mostreremmo "più informazioni" o "più cose".
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
// dopo scrollTo, ci sara' un evento "scroll", in modo da nascondere la freccia automaticamente
};

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 ...
// ... il vostro codice ...
</script>

</body>
Expand Down
12 changes: 6 additions & 6 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 @@ -4,13 +4,13 @@ importance: 5

# Up/down button

Create a "to the top" button to help with page scrolling.
Create un pulsante "inizio della pagina" per venire in aiuto con lo scroll della pagina.

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.
Dovrebbe funzionare così:
- Se la pagina non è stata scrollata per almeno l'altezza della finestra, è invisibile.
- Se la pagina è stata scrollata per più dell'altezza della finestra, deve comparire una freccia "verso l'alto" nell'angolo in alto a sinistra. Se la pagina viene scrollata in alto, scompare.
- Se la freccia viene cliccata, la pagina scrolla verso l'alto.

Like this (top-left corner, scroll to see):
Come in questo esempio (nell'angolo in alto a sinsitra, scrollare per vedere):

[iframe border="1" height="200" link src="solution"]
16 changes: 8 additions & 8 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,24 +1,24 @@
The `onscroll` handler should check which images are visible and show them.
Il gestore `onscroll` dovrebbe controllare quali immagini sono visibili e mostrarle.

We also want to run it when the page loads, to detect immediately visible images and load them.
Vogliamo anche eseguirla al caricamento della pagina, per rilevare immediatamente le immagini visibili e caricarle.

The code should execute when the document is loaded, so that it has access to its content.
Il codice dovrebbe essere eseguito al caricamento del documento, in modo che abbia accesso al suo contenuto.

Or put it at the `<body>` bottom:
Oppure, per fare ciò, si potrebbe mettere alla del `<body>`:

```js
// ...the page content is above...
// ...il contenuto della pagina sta sopra...

function isVisible(elem) {

let coords = elem.getBoundingClientRect();

let windowHeight = document.documentElement.clientHeight;

// top elem edge is visible?
// il bordo superiore dell'elemento risulta visibile?
let topVisible = coords.top > 0 && coords.top < windowHeight;

// bottom elem edge is visible?
// il bordo inferiore risulta visibile?
let bottomVisible = coords.bottom < windowHeight && coords.bottom > 0;

return topVisible || bottomVisible;
Expand Down Expand Up @@ -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. La soluzione ha anche una variante di `isVisible` che "precarica" le immagini che sono distano solo una pagina di scroll sopra o sotto lo scroll corrente del documento.
Original file line number Diff line number Diff line change
Expand Up @@ -165,25 +165,24 @@ <h1>Neptune</h1>

<script>
/**
* Tests if the element is visible (within the visible part of the page)
* It's enough that the top or bottom edge of the element are visible
* Controlla se l'elemento risulta visibile (all'interno della parte visibile della pagina)
* E' sufficiente che il bordo superiore o inferiore dell'elemento sia visibile
*/
function isVisible(elem) {

let coords = elem.getBoundingClientRect();

let windowHeight = document.documentElement.clientHeight;

// top elem edge is visible OR bottom elem edge is visible
// il bordo superiore dell'elemento OPPURE il bordo inferiore dell'elemento e' visibile
let topVisible = coords.top > 0 && coords.top < windowHeight;
let bottomVisible = coords.bottom < windowHeight && coords.bottom > 0;

return topVisible || bottomVisible;
}

/**
A variant of the test that considers the element visible if it's no more than
one page after/behind the current screen.
Una variante del test che considera l'elemento visibile se non siamo a più di una pagina di scroll di distanza prima o dopo la schermata attuale.

function isVisible(elem) {

Expand All @@ -194,7 +193,7 @@ <h1>Neptune</h1>
let extendedTop = -windowHeight;
let extendedBottom = 2 * windowHeight;

// top visible || bottom visible
// parte superiore visibile || parte inferiore visibile
let topVisible = coords.top > extendedTop && coords.top < extendedBottom;
let bottomVisible = coords.bottom < extendedBottom && coords.bottom > extendedTop;

Expand All @@ -208,8 +207,8 @@ <h1>Neptune</h1>
if (!realSrc) continue;

if (isVisible(img)) {
// disable caching
// this line should be removed in production code
// disabilita il caching
// la seguente riga dovrebbe essere rimossa in produzione
realSrc += '?nocache=' + Math.random();

img.src = realSrc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,11 @@ <h1>Neptune</h1>

<script>
/**
* Tests if the element is visible (within the visible part of the page)
* It's enough that the top or bottom edge of the element are visible
* Controlla se l'elemento risulta visibile (all'interno della parte visibile della pagina)
* E' sufficiente che il bordo superiore o inferiore dell'elemento sia visibile
*/
function isVisible(elem) {
// todo: your code
// todo: il vostro codice
}

function showVisible() {
Expand All @@ -178,8 +178,8 @@ <h1>Neptune</h1>
if (!realSrc) continue;

if (isVisible(img)) {
// disable caching
// this line should be removed in production code
// disabilita il caching
// la seguente riga dovrebbe essere rimossa in produzione
realSrc += '?nocache=' + Math.random();

img.src = realSrc;
Expand Down
24 changes: 12 additions & 12 deletions 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,29 @@ importance: 4

---

# Load visible images
# Caricare immagini visibili

Let's say we have a slow-speed client and want to save their mobile traffic.
Ipotizziamo di avere un client con connessione lenta e di voler far risparmiare un po' di traffico dal dispositivo mobile.

For that purpose we decide not to show images immediately, but rather replace them with placeholders, like this:
A questo proposito, decidiamo di non caricare immediatamente le immagini, ma piuttosto di sostituirle con dei segnaposto, così:

```html
<img *!*src="placeholder.svg"*/!* width="128" height="128" *!*data-src="real.jpg"*/!*>
```

So, initially all images are `placeholder.svg`. When the page scrolls to the position where the user can see the image -- we change `src` to the one in `data-src`, and so the image loads.
Quindi, inizialmente tutte le immagini saranno sostituite da un segnaposto `placeholder.svg`. Quando la pagina viene scrollata fino alla posizione in cui possiamo vedere le singole immagini, andiamo a modificare l'attributo `src` sostituendolo con il valore del `data-src`, in modo che l'immagine venga finalmente caricata.

Here's an example in `iframe`:
Ecco un esempio dentro l'`iframe`:

[iframe src="solution"]

Scroll it to see images load "on-demand".
Scrollare per vedere le immagini "a richiesta".

Requirements:
- When the page loads, those images that are on-screen should load immediately, prior to any scrolling.
- Some images may be regular, without `data-src`. The code should not touch them.
- Once an image is loaded, it should not reload any more when scrolled in/out.
Requisiti:
- Quando la pagina viene caricata, le immagini che sono sullo schermo dovrebbero caricarsi immediatamente, prima di qualunque scroll.
- Alcune immagini potrebbero essere normali, prive dell'attributo `data-src`. Queste immagini non dovrebbero essere influenzate dal nostro codice.
- Una volta che l'immagine viene caricata, non dovrebbe più caricarsi, a prescindere che se si stia scrollando oltre o che l'elemento che la contenga torni nuovamente ad essere visibile sullo schermo.

P.S. If you can, make a more advanced solution that would "preload" images that are one page below/after the current position.
P.S. Se potete, create una soluzione avanzata che effettui un "preload" delle immagini che sono poco sotto la posizione attuale.

P.P.S. Only vertical scroll is to be handled, no horizontal scrolling.
P.P.S. Si deve gestire solamente lo scroll verticale, e non quello orizzontale.
30 changes: 15 additions & 15 deletions 2-ui/3-event-details/8-onscroll/article.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Scrolling

The `scroll` event allows reacting to a page or element scrolling. There are quite a few good things we can do here.
L'evento `scroll` permette di reagire allo scroll della pagina o di un elemento. Ci sono poche e semplici operazioni che possiamo compiere in questi casi.

For instance:
- Show/hide additional controls or information depending on where in the document the user is.
- Load more data when the user scrolls down till the end of the page.
Per esempio:
- Mostrare/nascondere controlli aggiuntivi o informazioni, a seconda della posizione del documento in cui si trova l'utente.
- Caricare più dati quando l'utente scolla fino in fondo alla pagina.

Here's a small function to show the current scroll:
Ecco una piccola funzione per mostrare lo scroll del documento:

```js autorun
window.addEventListener('scroll', function() {
Expand All @@ -15,23 +15,23 @@ window.addEventListener('scroll', function() {
```

```online
In action:
Eccolo in azione:

Current scroll = <b id="showScroll">scroll the window</b>
Scroll attuale = <b id="showScroll">Scrolla la finestra</b>
```

The `scroll` event works both on the `window` and on scrollable elements.
L'evento `scroll` funziona sia sulla `window` che sugli elementi scrollabili.

## Prevent scrolling
## Prevenire lo scrolling

How do we make something unscrollable?
Come possiamo rendere qualcosa non scrollabile?

We can't prevent scrolling by using `event.preventDefault()` in `onscroll` listener, because it triggers *after* the scroll has already happened.
Sicuramente, non possiamo prevenire lo scrolling usando `event.preventDefault()` nel listener `onscroll`, perché quest'ultimo viene generato *dopo* che lo scroll è avvenuto.

But we can prevent scrolling by `event.preventDefault()` on an event that causes the scroll, for instance `keydown` event for `key:pageUp` and `key:pageDown`.
Tuttavia, possiamo prevenire lo scrolling con l'utilizzo di `event.preventDefault()` con altri eventi che permettono lo scroll, ad esempio l'evento `keydown` per `key:pageUp` e `key:pageDown`.

If we add an event handler to these events and `event.preventDefault()` in it, then the scroll won't start.
Se aggiungiamo un gestore a uno di questi eventi, utilizzando `event.preventDefault()`, allora lo scroll non comincerà affatto.

There are many ways to initiate a scroll, so it's more reliable to use CSS, `overflow` property.
Ci sono vari modi per inizializzare uno scroll, al punto tale che spesso è più affidabile usare i CSS tramite la proprietà `overflow`.

Here are few tasks that you can solve or look through to see applications of `onscroll`.
Ecco alcune attività che potrete risolvere o analizzare per vedere le applicazioni di `onscroll`.
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy