The PageComponent has almost the same events as the ScrollComponent, plus a page change event.
|Start of momentum or bounce animation (use on |
|End of momentum or bounce animation (use on |
|The content is moving (includes momentum or bounce animation)|
|The component just snapped to a page|
onScrollAnimationDidEnd don’t work on a PageComponent, but we can listen to the animation events of the
When working with
"change:currentPage", two PageComponent properties will come in handy:
currentPagecontains the currently visible page
previousPageholds the page that just scrolled off screen
In this example, the current page is set to full opacity (on every page change) while the previous page is faded out:
# Listen to page switches page.on "change:currentPage", -> # current page: full opacity page.currentPage.animate opacity: 1 options: time: 0.4 # previous page: half opacity page.previousPage.animate opacity: 0.5 options: time: 0.4
(In the project, I gave the pages an
0.5 when creating them.)
Say you’re using page indicators (the small dots at the bottom of the page denoting the total number of pages). You’ll want to know which page is visible at a given time in order to highlight the correct indicator.
currentPage property doesn’t give you the ordinal number of the current page, but you can get it with one more line of code.
You can pass a layer object to
horizontalPageIndex() to look up the index of that page. (For vertically stacked pages: use
An example. First, we create the indicators. We can do it in the same loop that we use to make the pages.
# indicator for every page indicator = new Layer size: 12, borderRadius: "50%" backgroundColor: "white" y: 630 x: 98 + (index * 24) opacity: 0.2 parent: page # add indicator to array allIndicators.push indicator
The indicators have an opacity of
0.2 and we use
index to place each dot
24 points farther to the right.
Note that they have
page as their
parent (and not
page.content), so they’ll stay in the same position.
The indicators were added to an
allIndicators array, so the first indicator in the array will have an index of
0. We can already give this one full opacity, since the first page will be visible at the start.
# set indicator for the first page allIndicators.opacity = 1
Now we listen to
"change:currentPage" to set the correct indicator after every page change:
# update indicators on page change page.on "change:currentPage", -> # reset all for indicator in allIndicators indicator.opacity = 0.2 # set full opacity for active page current = page.horizontalPageIndex page.currentPage allIndicators[current].opacity = 1
In the code above we give all the indicators an
0.2, to have a clean slate.
We then get the horizontal page index by passing
page.horizontalPageIndex(), and use the result (
current) to set the opacity of the indicator in question in the