|
8 | 8 | lightbox: true
|
9 | 9 | ---
|
10 | 10 |
|
11 |
| -```{ojs} |
12 |
| -//| echo: false |
13 |
| -//| output: false |
14 | 11 |
|
15 |
| -// Load the pre-fetched cat data |
16 |
| -cats = FileAttachment("../_data/cats.json").json() |
17 |
| -console.log(cats) |
18 |
| -
|
19 |
| -viewof carousel = { |
20 |
| - const wrapper = html`<div class="carousel-wrapper"></div>`; |
21 |
| - |
22 |
| - // No need for .then() as cats is already resolved |
23 |
| - cats.forEach(cat => { |
24 |
| - const img = document.createElement('img'); |
25 |
| - img.src = cat.url; |
26 |
| - img.alt = 'Cat image'; |
27 |
| - wrapper.appendChild(img); |
28 |
| - }); |
29 |
| - |
30 |
| - return wrapper; |
31 |
| -} |
32 |
| -``` |
33 | 12 |
|
34 | 13 | In the terminology of APIs, an **endpoint** is a URL that specifies the location of a resource on a server. As we saw with the cat API, most of the time you can access the data from an endpoint without requiring any particular software besides a web browser.
|
35 | 14 |
|
@@ -91,6 +70,49 @@ With this result:
|
91 | 70 | <button class="carousel-button next">→</button>
|
92 | 71 | </div>
|
93 | 72 |
|
| 73 | +```{ojs} |
| 74 | +cats = FileAttachment("../_data/cats.json").json() |
| 75 | +
|
| 76 | +viewof carousel = { |
| 77 | + const container = html` |
| 78 | + <div class="carousel-container"> |
| 79 | + <div class="carousel-wrapper"></div> |
| 80 | + <button class="carousel-button prev">←</button> |
| 81 | + <button class="carousel-button next">→</button> |
| 82 | + </div> |
| 83 | + `; |
| 84 | + |
| 85 | + const wrapper = container.querySelector('.carousel-wrapper'); |
| 86 | + |
| 87 | + cats.forEach(cat => { |
| 88 | + const img = document.createElement('img'); |
| 89 | + img.src = cat.url; |
| 90 | + img.alt = 'Cat image'; |
| 91 | + wrapper.appendChild(img); |
| 92 | + }); |
| 93 | +
|
| 94 | + let currentIndex = 0; |
| 95 | + const totalImages = cats.length; |
| 96 | + |
| 97 | + function updateCarousel() { |
| 98 | + wrapper.style.transform = `translateX(-${currentIndex * 100}%)`; |
| 99 | + } |
| 100 | +
|
| 101 | + container.querySelector('.next').addEventListener('click', () => { |
| 102 | + currentIndex = (currentIndex + 1) % totalImages; |
| 103 | + updateCarousel(); |
| 104 | + }); |
| 105 | +
|
| 106 | + container.querySelector('.prev').addEventListener('click', () => { |
| 107 | + currentIndex = (currentIndex - 1 + totalImages) % totalImages; |
| 108 | + updateCarousel(); |
| 109 | + }); |
| 110 | + |
| 111 | + return container; |
| 112 | +} |
| 113 | +``` |
| 114 | + |
| 115 | + |
94 | 116 | <script>
|
95 | 117 | document.addEventListener('DOMContentLoaded', async () => {
|
96 | 118 | try {
|
|
0 commit comments