### Install Auto Height Plugin (CDN)
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/plugins/auto-height.mdx
Install the Auto Height plugin using a CDN link. This is useful for quick setup or when not using a package manager.
```html
```
--------------------------------
### Basic Carousel Setup - JavaScript
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/examples/predefined.mdx
Demonstrates fundamental Embla Carousel configurations including default, loop, right-to-left, slides to scroll, drag-free, alignment, variable widths, Y-axis, slides per view, and thumbnail navigation. These examples require minimal setup and showcase core carousel behaviors.
```javascript
import { ExampleDefault } from '@/content/v9/examples/Predefined/Basic/DefaultLazy'
import { ExampleLoop } from '@/content/v9/examples/Predefined/Basic/LoopLazy'
import { ExampleRightToLeft } from '@/content/v9/examples/Predefined/Basic/RightToLeftLazy'
import { ExampleSlidesToScroll } from '@/content/v9/examples/Predefined/Basic/SlidesToScrollLazy'
import { ExampleDragFree } from '@/content/v9/examples/Predefined/Basic/DragFreeLazy'
import { ExampleAlign } from '@/content/v9/examples/Predefined/Basic/AlignLazy'
import { ExampleVariableWidths } from '@/content/v9/examples/Predefined/Basic/VariableWidthsLazy'
import { ExampleYAxis } from '@/content/v9/examples/Predefined/Basic/YAxisLazy'
import { ExampleSlidesPerView } from '@/content/v9/examples/Predefined/Basic/SlidesPerViewLazy'
import { ExampleThumbs } from '@/content/v9/examples/Predefined/Basic/ThumbsLazy'
```
--------------------------------
### Basic Embla Carousel Setup (React)
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/required-setup.html
This example shows the fundamental React component structure for initializing Embla Carousel. Ensure you have the necessary imports and the correct DOM structure.
```jsx
function MyCarousel() {
const emblaRef = useRef(emblaCarousel())
return (
Slide 1
Slide 2
Slide 3
{/* Optional: Add navigation controls here */}
)
}
```
--------------------------------
### Install Autoplay Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/get-started/module/__next.docs.$oc$slug.__PAGE__.txt
Install the Autoplay plugin using your preferred package manager.
```shell
npm install embla-carousel-autoplay --save
```
```shell
pnpm add embla-carousel-autoplay
```
```shell
yarn add embla-carousel-autoplay
```
--------------------------------
### Autoplay Plugin Installation
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/plugins/autoplay.mdx
Install the Autoplay plugin using various package managers.
```APIDOC
## Autoplay Plugin Installation
Start by installing the **npm package** and save it to your dependencies:
### CDN
```html
```
### NPM
```shell
npm install embla-carousel-autoplay
```
### Yarn
```shell
yarn add embla-carousel-autoplay
```
### PNPM
```shell
pnpm add embla-carousel-autoplay
```
**Note:** You need to call the `play()` method to start autoplay:
```js
emblaApi.plugins().autoplay?.play()
```
```
--------------------------------
### Install Wheel Gestures Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/wheel-gestures.txt
Install the wheel gestures plugin using npm or yarn.
```bash
npm install @embla-carousel/react
# or
yarn add @embla-carousel/react
```
--------------------------------
### SSR CSS Setup
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/guides/server-side-rendering.mdx
Basic CSS setup for server-side rendering with Embla Carousel.
```less
.embla {
overflow: hidden;
}
.embla__container {
display: flex;
}
.embla__slide {
flex: 0 0 100%;
}
```
--------------------------------
### Install Auto Scroll Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/auto-scroll.txt
Install the auto-scroll package using npm or yarn.
```bash
npm install @embla-carousel/react-auto-scroll
# or
yarn add @embla-carousel/react-auto-scroll
```
--------------------------------
### Initialize Embla Carousel with Autoplay Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/get-started/cdn/__next.docs.$oc$slug.__PAGE__.txt
Initialize Embla Carousel and include the Autoplay plugin by passing it in the plugins array. This example also shows how to start the autoplay after initialization. Ensure the Autoplay plugin is loaded via CDN.
```html
```
--------------------------------
### Accessibility Plugin Installation
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/plugins/accessibility.mdx
Install the Accessibility plugin using npm, yarn, pnpm, or CDN.
```APIDOC
## Installation
Start by installing the **npm package** and save it to your dependencies:
**Note:** To honor [prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion) user settings, it is recommended to add a media query in the `breakpoints` option of the carousel constructor.
Learn more about the [`breakpoints`](/docs/api/options#breakpoints) option.
```
--------------------------------
### Run Development Server
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/README.md
Use these commands to start the development server for the Next.js project. Open http://localhost:3000 in your browser to view the application.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Interactive Slide Gaps Example
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/slide-gaps/__next.docs.$oc$slug.__PAGE__.txt
This interactive example showcases how slide gaps are visually represented and function within Embla Carousel. It requires React and Embla Carousel setup.
```jsx
import React from 'react';
import useEmblaCarousel from 'embla-carousel-react';
import { EmblaCarouselType } from 'embla-carousel'
import { DotButton, useDotButton } from './EmblaCarouselDotButton'
import { PrevButton, NextButton, usePrevNextButtons } from './EmblaCarouselPrevNextButton'
import './embla.css'
type PropType = {
slides: number[]
options?: EmblaCarouselType['options']
}
const EmblaCarousel = (props: PropType) => {
const { slides, options } = props
const [emblaRef, emblaApi] = useEmblaCarousel(options)
const { selectedIndex, scrollSnaps, onDotClick, ...rest } = useDotButton(emblaApi)
const { prevBtnDisabled, nextBtnDisabled, onPrev, onNext } = usePrevNextButtons(emblaApi)
return (
<>
>
)
}
export default EmblaCarousel
```
--------------------------------
### Initialize Auto Height Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/auto-height/__next._index.txt
Learn how to enable and configure the auto-height plugin when initializing Embla Carousel. This example shows basic setup.
```javascript
import EmblaCarousel from 'embla-carousel'
import Autoplay from 'embla-carousel-autoplay'
import AutoHeight from 'embla-carousel-auto-height'
const emblaNode = document.querySelector('.embla')
const options = {
loop: false
}
const plugins = [
Autoplay({
delay: 4000,
stopOnInteraction: false
}),
AutoHeight()
]
const emblaApi = EmblaCarousel(emblaNode, options, plugins)
console.log(emblaApi.plugins.autoHeight.options)
```
--------------------------------
### Vue Autoplay Plugin Example
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/plugins.html
Integrates the Autoplay plugin with Embla Carousel in a Vue.js application. Ensure to install 'embla-carousel-autoplay' as a dev dependency if using pnpm.
```html
Slide 1
Slide 2
Slide 3
```
--------------------------------
### Create a Basic React Carousel Component
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/get-started/react/__next.docs.$oc$slug.__PAGE__.txt
Use the `useEmblaCarousel` hook to create a functional carousel component in React. This example shows basic navigation setup.
```jsx
import React from 'react'
import useEmblaCarousel from 'embla-carousel-react'
export function EmblaCarousel() {
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false })
const goToPrev = () => emblaApi?.goToPrev()
const goToNext = () => emblaApi?.goToNext()
return (
Slide 1
Slide 2
Slide 3
)
}
```
--------------------------------
### Listen for Slides In View Event (Vanilla JS)
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events.html
Subscribe to the 'slidesinview' event to get information about which slides are currently visible. This example uses vanilla JavaScript.
```javascript
import EmblaCarousel from 'embla-carousel'
const wrapperNode = document.querySelector('.embla')
const viewportNode = wrapperNode.querySelector('.embla__viewport')
const emblaApi = EmblaCarousel(viewportNode, { loop: true })
const logSlidesInView = (emblaApi, event) => {
console.log(`${event.type}: ${event.detail.slidesInView}`)
}
emblaApi.on('slidesinview', logSlidesInView)
```
```html
Slide 1
Slide 2
Slide 3
```
--------------------------------
### Initialize Embla Carousel with Options (SolidJS)
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/options.html
Provides an example of setting up Embla Carousel in a SolidJS project with the 'loop' option configured to true, using the 'embla-carousel-solid' adapter.
```jsx
import useEmblaCarousel from 'embla-carousel-solid'
export function EmblaCarousel() {
const [emblaRef] = useEmblaCarousel(() => ({ loop: true }))
return (
Slide 1
Slide 2
Slide 3
)
```
```html
Slide 1
Slide 2
Slide 3
```
--------------------------------
### Install Fade Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/fade.txt
Install the fade plugin using npm or yarn. This is required before using fade transitions.
```bash
npm install @embla-carousel/react
# or
```
```bash
yarn add @embla-carousel/react
```
--------------------------------
### Embla Carousel Core Package Options
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/options.html
The `EmblaOptionsType` comes from the core `embla-carousel` package and can be used to configure the carousel. This example shows basic setup with HTML structure.
```ts
import EmblaCarousel, { EmblaOptionsType } from 'embla-carousel'
const wrapperNode = document.querySelector('.embla')
const viewportNode = wrapperNode.querySelector('.embla__viewport')
const options: EmblaOptionsType = { loop: true }
const emblaApi = EmblaCarousel(viewportNode, options)
```
```html
Slide 1
Slide 2
Slide 3
```
--------------------------------
### Initialize Theme and Apply CSS Classes
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/_not-found/__next._index.txt
This script initializes the theme by checking local storage and system preferences. It applies the corresponding CSS class ('theme-light' or 'theme-dark') to the document element and updates the `theme-color` meta tag. It also stores the current theme in `window.__THEME__`.
```javascript
(function() {
let selectedTheme;
const themeColors = {
light: 'rgb(249, 249, 249)',
dark: 'rgb(5, 5, 5)'
};
try {
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
const themeKey = selectedTheme || preferredTheme || 'light';
const oppositeKey = themeKey === 'light' ? 'dark' : 'light';
document.documentElement.classList.remove('theme-' + oppositeKey);
document.documentElement.classList.add('theme-' + themeKey);
const themeColorElement = document.querySelector("meta[name='theme-color']");
if (themeColorElement) themeColorElement.setAttribute('content', themeColors[themeKey]);
window.__THEME__ = themeKey;
})();
```
--------------------------------
### Embla Carousel Vue Setup
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/required-setup.html
Set up Embla Carousel in a Vue.js project using the `embla-carousel-vue` package. This example shows how to use the `useEmblaCarousel` composable and bind the ref.
```html
Slide 1
Slide 2
Slide 3
```
--------------------------------
### Theme Initialization Logic
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events/__next._full.txt
Initializes theme based on local storage or system preferences. Handles potential errors during local storage access.
```javascript
(function() {
let selectedTheme;
const themeColors = {
light: 'rgb(249, 249, 249)',
dark: 'rgb(5, 5, 5)'
};
try {
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
```
--------------------------------
### Embla Carousel React Setup
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/required-setup.html
Integrate Embla Carousel into a React application using the `embla-carousel-react` hook. This example demonstrates how to attach the carousel ref to the viewport element.
```jsx
import React from 'react'
import useEmblaCarousel from 'embla-carousel-react'
export function EmblaCarousel() {
const [emblaRef] = useEmblaCarousel()
return (
Slide 1
Slide 2
Slide 3
{/\* Optional: Add navigation controls here * /}
)
}
```
--------------------------------
### Accessibility Plugin Setup Methods
Source: https://github.com/davidjerleke/embla-carousel/blob/master/website/src/content/v9/pages/plugins/accessibility.mdx
Methods for setting up accessibility features for previous/next buttons, dot buttons, and live regions.
```APIDOC
## POST /emblaApi/plugins().accessibility?.setupPrevAndNextButtons
### Description
Registers the previous and next buttons for the carousel, allowing the Accessibility plugin to add appropriate ARIA attributes and labels to them. Provide an element or a selector string for each button.
### Method
POST
### Endpoint
/emblaApi/plugins().accessibility?.setupPrevAndNextButtons
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **prevButton** (HTMLElement | string) - Required - The previous button element or selector.
- **nextButton** (HTMLElement | string) - Required - The next button element or selector.
### Request Example
```json
{
"prevButton": ".embla__prev-button",
"nextButton": ".embla__next-button"
}
```
### Response
#### Success Response (200)
- **void** - This method does not return a value.
#### Response Example
```json
null
```
---
## POST /emblaApi/plugins().accessibility?.setupDotButtons
### Description
Registers the dot buttons wrapper for the carousel, allowing the Accessibility plugin to add appropriate ARIA attributes and labels to each dot button. Provide an element or a selector string for the dots wrapper.
### Method
POST
### Endpoint
/emblaApi/plugins().accessibility?.setupDotButtons
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **dotsWrapper** (HTMLElement | string) - Required - The dots wrapper element or selector.
### Request Example
```json
{
"dotsWrapper": ".embla__dots"
}
```
### Response
#### Success Response (200)
- **void** - This method does not return a value.
#### Response Example
```json
null
```
---
## POST /emblaApi/plugins().accessibility?.setupLiveRegion
### Description
Registers the live region element for the carousel, allowing the Accessibility plugin to announce slide changes to assistive technologies. Provide an element or a selector string for the live region.
### Method
POST
### Endpoint
/emblaApi/plugins().accessibility?.setupLiveRegion
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **liveRegion** (HTMLElement | string) - Required - The live region element or selector.
### Request Example
```json
{
"liveRegion": ".embla__live-region"
}
```
### Response
#### Success Response (200)
- **void** - This method does not return a value.
#### Response Example
```json
null
```
### Note
The [`announceChanges`](#announcechanges) option must be set to `true` for this to work.
```
--------------------------------
### Get Carousel Scroll Progress
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/methods/__next.docs.$oc$slug.__PAGE__.txt
Call this method on the Embla API instance to retrieve the current scroll progress of the carousel. The value ranges from 0 (start) to 1 (end).
```typescript
emblaApi.scrollProgress()
```
--------------------------------
### Install Wheel Gestures Plugin via npm
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/wheel-gestures/__next.docs.$oc$slug.__PAGE__.txt
Install the Wheel Gestures plugin using npm for your project.
```shell
npm install embla-carousel-wheel-gestures --save
```
--------------------------------
### Type Callback Constant in TypeScript
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events.html
When using pnpm, explicitly install `embla-carousel` as a devDependency if you import types from it. This example shows how to assign types to a callback constant using `EmblaEventCallbackType`.
```typescript
import { EmblaEventCallbackType } from 'embla-carousel'
const logPointerDown: EmblaEventCallbackType<'pointerdown'> = (
emblaApi,
event
) => {
console.log(event) // Will contain correct event type and detail
}
```
--------------------------------
### Initialize Theme Based on User Preference
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/index.txt
This script initializes the theme by checking local storage for a saved theme, then checking the user's system preference, and defaulting to 'light' if neither is found. It applies the appropriate theme class to the document element.
```javascript
(function() {
let selectedTheme;
const themeColors = {
light: 'rgb(249, 249, 249)',
dark: 'rgb(5, 5, 5)'
};
try {
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
const themeKey = selectedTheme || preferredTheme || 'light';
const oppositeKey = themeKey === 'light' ? 'dark' : 'light';
document.documentElement.classList.remove('theme-' + oppositeKey);
document.documentElement.classList.add('theme-' + themeKey);
})();
```
--------------------------------
### Install Wheel Gestures Plugin via CDN
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/wheel-gestures.html
Include this script tag to add the Wheel Gestures plugin using a CDN. This is useful for quick setup or when not using a module bundler.
```html
```
--------------------------------
### Basic Embla Carousel Component in React
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/get-started/react.html
This component demonstrates a functional Embla Carousel setup with basic slides and navigation buttons. It requires Embla Carousel and its React adapter to be installed.
```jsx
import React, { useState, useEffect, useRef } from "react";
import useEmblaCarousel from "embla-carousel-react";
import "./styles.css";
export const EmblaCarousel = () => {
const [emblaRef, emblaApi] = useEmblaCarousel();
const [prevBtnEnabled, setPrevBtnEnabled] = useState(false);
const [nextBtnEnabled, setNextBtnEnabled] = useState(false);
const onSelect = () => {
setPrevBtnEnabled(emblaApi.canScrollPrev());
setNextBtnEnabled(emblaApi.canScrollNext());
};
const scrollPrev = () => emblaApi.scrollPrev();
const scrollNext = () => emblaApi.scrollNext();
useEffect(() => {
if (!emblaApi) return;
onSelect();
emblaApi.on("select", onSelect);
emblaApi.on("reInit", onSelect);
}, [emblaApi]);
return (
Slide 1
Slide 2
Slide 3
);
};
```
--------------------------------
### Handle 'select' event in TypeScript
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events.html
Listen for the 'select' event to get the previous and current snap indexes when the carousel changes slides. Ensure 'embla-carousel' is installed as a devDependency if using pnpm.
```typescript
import EmblaCarouselType, { EmblaEventModelType } from 'embla-carousel'
const logSelectEvent = (
emblaApi: EmblaCarouselType,
event: EmblaEventModelType<'select'>
): void => {
const { sourceSnap, targetSnap } = event.detail
console.log('Previous snap index: ', sourceSnap)
console.log('Current snap index: ', targetSnap)
}
// Usage:
// emblaApi.on('select', logSelectEvent)
```
--------------------------------
### Autoplay with Custom Options
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/autoplay/__next.docs.$oc$slug.__PAGE__.txt
Demonstrates how to initialize the Autoplay plugin with custom options, such as stopping on the last snap.
```typescript
import Autoplay from "embla-carousel-autoplay";
const emblaApi = EmblaCarousel(emblaNode, {
plugins: [
Autoplay({
stopOnLastSnap: true
})
]
});
```
--------------------------------
### Svelte: Handling Initialization Event
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events.html
This example shows how to use the `on:emblainit` event in Svelte to get the Embla API instance and attach event listeners. It logs the slides in view once after initialization.
```APIDOC
## Svelte: Handling Initialization Event
### Description
This example shows how to use the `on:emblainit` event in Svelte to get the Embla API instance and attach event listeners. It logs the slides in view once after initialization.
### Method
Svelte Component Event Handler
### Endpoint
`on:emblainit`
### Parameters
#### Event Payload
- **event** (object) - Contains `detail` object with the Embla API instance.
- **event.detail** (EmblaApi) - The Embla Carousel API instance.
### Request Example
```svelte
Slide 1
Slide 2
Slide 3
```
### Response
#### Success Response
- The `emblaApi` variable will be populated with the Embla Carousel API instance.
#### Response Example
```json
// Console output when slides come into view:
// slidesinview: [0, 1, 2]
```
### Notes
- Starting with Svelte 5, the `on:` event handlers have been deprecated. However, `on:emblainit` will remain for backward compatibility.
```
--------------------------------
### Install Fade Plugin via npm
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/fade.html
Save the Fade plugin to your project's dependencies using npm. This is the first step to enable fade transitions.
```bash
npm install @embla-carousel/react
npm install embla-carousel-fade
```
--------------------------------
### Basic Fade Transition Setup
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/fade.txt
Set up Embla Carousel with the fade transition. Ensure the plugin is imported and applied to the carousel instance.
```jsx
import React from 'react';
import useEmblaCarousel from 'embla-carousel-react';
import './embla.css';
const EmblaFade = () => {
const [emblaRef] = useEmblaCarousel({ loop: false }, [
// fade
]);
return (
1
2
3
);
};
export default EmblaFade;
```
--------------------------------
### Solid.js Autoplay Plugin Example
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/plugins/__next.docs.$oc$slug.__PAGE__.txt
Demonstrates using the Autoplay plugin with Embla Carousel in a Solid.js application. When using pnpm and importing types from 'embla-carousel', ensure 'embla-carousel' is installed as a devDependency.
```tsx
/** @jsxImportSource solid-js */
import { createEffect, createSignal, on } from 'solid-js'
import { EmblaPluginType } from 'embla-carousel'
import useEmblaCarousel from 'embla-carousel-solid'
import Autoplay from 'embla-carousel-autoplay'
export function EmblaCarousel() {
const [plugins, setPlugins] = createSignal([Autoplay()])
const [emblaRef, emblaApi] = useEmblaCarousel(() => ({ loop: true }), plugins)
createEffect(
on(emblaApi, (api) => {
if (!api) return
api.plugins().autoplay?.play()
})
)
return (
Slide 1
Slide 2
Slide 3
)
}
```
--------------------------------
### Install Autoplay Plugin with npm
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/plugins/__next.docs.$oc$slug.__PAGE__.txt
Use npm to install the Autoplay plugin. This is the standard package manager for Node.js projects.
```shell
npm install embla-carousel-autoplay --save
```
--------------------------------
### Embla Carousel with Dot Navigation (SolidJS)
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/dot-buttons.html
Utilize SolidJS to implement dot navigation for Embla Carousel. This example shows the setup for signals, effects, and event handling to create interactive dots.
```javascript
import { createSignal, createEffect, on, For } from 'solid-js'
import useEmblaCarousel from 'embla-carousel-solid'
export function EmblaCarousel() {
const [emblaRef, emblaApi] = useEmblaCarousel(() => ({
loop: false
}))
const [scrollSnaps, setScrollSnaps] = createSignal([])
const [selectedSnap, setSelectedSnap] = createSignal(0)
const goTo = (index) => emblaApi()?.goTo(index)
const setupSnaps = (emblaApi) => setScrollSnaps(emblaApi.snapList())
```
--------------------------------
### snapList()
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/methods/__next.docs.$oc$slug.__PAGE__.txt
Returns an array of all scroll snap positions. Each value represents the carousel's progress required to reach that position, where 0 is the start and 1 is the end (for example, 0.5 = 50% progress).
```APIDOC
## snapList()
### Description
Returns an array of all scroll snap positions. Each value represents the carousel's progress required to reach that position, where 0 is the start and 1 is the end (for example, 0.5 = 50% progress).
### Method
```ts
emblaApi.snapList()
```
### Returns
- `number[]`: An array of scroll snap positions.
```
--------------------------------
### Initialize Theme and Color Scheme
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/required-setup.html
This script initializes the theme by checking local storage and user preferences for color schemes. It applies the appropriate theme class to the document element and sets the meta theme-color attribute.
```javascript
(() => {
let selectedTheme;
const themeColors = {
light: 'rgb(249, 249, 249)',
dark: 'rgb(5, 5, 5)'
};
try {
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
const themeKey = selectedTheme || preferredTheme || 'light';
const oppositeKey = themeKey === 'light' ? 'dark' : 'light';
document.documentElement.classList.remove('theme-' + oppositeKey);
document.documentElement.classList.add('theme-' + themeKey);
const themeColorElement = document.querySelector("meta[name='theme-color']");
if (themeColorElement) themeColorElement.setAttribute('content', themeColors[themeKey]);
window.__THEME__ = themeKey;
})();
```
--------------------------------
### setupLiveRegion
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/accessibility/__next._full.txt
Sets up a live region for accessibility, which announces carousel changes to screen readers. It accepts an HTML element or a selector string for the live region container.
```APIDOC
## setupLiveRegion
### Description
Sets up a live region for accessibility, which announces carousel changes to screen readers. It accepts an HTML element or a selector string for the live region container.
### Method
```ts
emblaApi.plugins().accessibility?.setupLiveRegion(liveRegion: HTMLElement | string)
```
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- **liveRegion** (HTMLElement | string) - Required - The element or selector string for the live region container.
### Request Example
```json
{
"example": "emblaApi.plugins().accessibility?.setupLiveRegion('.embla-live-region')"
}
```
### Response
#### Success Response (200)
- None (This method is for setup and does not return a value).
#### Response Example
```json
{
"example": "// No direct response"
}
```
```
--------------------------------
### snapList()
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/methods/__next._full.txt
Returns an array of all scroll snap positions. Each value represents the carousel's progress required to reach that position, where 0 is the start and 1 is the end (for example, 0.5 = 50% progress).
```APIDOC
## snapList()
### Description
Returns an array of all scroll snap positions. Each value represents the carousel's progress required to reach that position, where 0 is the start and 1 is the end (for example, 0.5 = 50% progress).
### Method
```ts
emblaApi.snapList()
```
### Returns
- Array of numbers representing scroll snap positions.
```
--------------------------------
### Solid.js: Handling Select Event
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/events.html
This example demonstrates how to use the `useEmblaCarousel` hook in Solid.js to get the Embla API instance and attach a listener for the 'select' event, logging the previous and current snap indexes.
```APIDOC
## Solid.js: Handling Select Event
### Description
This example demonstrates how to use the `useEmblaCarousel` hook in Solid.js to get the Embla API instance and attach a listener for the 'select' event, logging the previous and current snap indexes.
### Method
Solid.js Custom Hook and Effect
### Endpoint
`useEmblaCarousel` hook and `createEffect` with `on(emblaApi, ...)`
### Parameters
#### `useEmblaCarousel` Hook Arguments
- **(api) => options** (function) - A function that returns the carousel options.
#### `createEffect` Callback Arguments
- **api** (EmblaCarouselType | undefined) - The Embla Carousel API instance.
#### `select` Event Payload
- **event** (EmblaEventModelType<'select'>) - The event object containing snap index details.
- **event.detail** (object)
- **sourceSnap** (number) - The previous snap index.
- **targetSnap** (number) - The current snap index.
### Request Example
```jsx
/* @jsxImportSource solid-js */
import { createEffect, on } from 'solid-js'
import { EmblaCarouselType, EmblaEventModelType } from 'embla-carousel'
import useEmblaCarousel from 'embla-carousel-solid'
export function EmblaCarousel() {
const [emblaRef, emblaApi] = useEmblaCarousel(() => ({ loop: true }))
const logSelectEvent = (
emblaApi: EmblaCarouselType,
event: EmblaEventModelType<'select'>
): void => {
const { sourceSnap, targetSnap } = event.detail
console.log('Previous snap index: ', sourceSnap)
console.log('Current snap index: ', targetSnap)
}
createEffect(
on(emblaApi, (api) => {
if (!api) return
api.on('select', logSelectEvent)
})
)
return (
Slide 1
Slide 2
Slide 3
)
}
```
### Response
#### Success Response
- The `emblaApi` variable will be populated with the Embla Carousel API instance.
- The `select` event listener will be attached.
#### Response Example
```json
// Console output when slides change:
// Previous snap index: 0
// Current snap index: 1
```
```
--------------------------------
### Initialize Theme Management Script
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/methods/__next._full.txt
This script handles theme initialization by checking local storage, user preferences, and applying the appropriate theme class and meta tag content to the document. It also sets a global `__THEME__` variable.
```javascript
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
const themeKey = selectedTheme || preferredTheme || 'light';
const oppositeKey = themeKey === 'light' ? 'dark' : 'light';
document.documentElement.classList.remove('theme-' + oppositeKey);
document.documentElement.classList.add('theme-' + themeKey);
const themeColorElement = document.querySelector("meta[name='theme-color']");
if (themeColorElement) themeColorElement.setAttribute('content', themeColors[themeKey]);
window.__THEME__ = themeKey;
})();
```
--------------------------------
### Initialize Embla Carousel with Autoplay Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/get-started/cdn.txt
Initialize Embla Carousel and pass the Autoplay plugin as the third argument to the constructor. This example also shows basic navigation event listeners and starting autoplay.
```javascript
const wrapperNode = document.querySelector('.embla')
const viewportNode = wrapperNode.querySelector('.embla__viewport')
const prevButtonNode = wrapperNode.querySelector('.embla__prev')
const nextButtonNode = wrapperNode.querySelector('.embla__next')
const emblaApi = EmblaCarousel(viewportNode, { loop: false }, [
EmblaCarouselAutoplay()
])
prevButtonNode.addEventListener('click', () => emblaApi.goToPrev(), false)
nextButtonNode.addEventListener('click', () => emblaApi.goToNext(), false)
emblaApi.plugins().autoplay?.play()
```
--------------------------------
### Initialize Theme
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/examples/predefined/__next._full.txt
Initializes the theme based on local storage, user preference, or a default. It applies CSS classes and sets the theme-color meta tag.
```javascript
let selectedTheme;
const themeColors = {
light: 'rgb(249, 249, 249)',
dark: 'rgb(5, 5, 5)'
};
try {
const themeStorage = localStorage.getItem('theme');
selectedTheme = (JSON.parse(themeStorage) || {}).currentTheme;
} catch (error) {
console.error(error);
}
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches && 'dark';
const themeKey = selectedTheme || preferredTheme || 'light';
const oppositeKey = themeKey === 'light' ? 'dark' : 'light';
document.documentElement.classList.remove('theme-' + oppositeKey);
document.documentElement.classList.add('theme-' + themeKey);
const themeColorElement = document.querySelector("meta[name='theme-color']");
if (themeColorElement) themeColorElement.setAttribute('content', themeColors[themeKey]);
window.__THEME__ = themeKey;
```
--------------------------------
### Svelte Component with Autoplay Plugin
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/api/plugins/__next.docs.$oc$slug.__PAGE__.txt
This Svelte component initializes Embla Carousel with the Autoplay plugin enabled. It sets up options for looping and starts the autoplay on initialization. Ensure Embla Carousel and the Autoplay plugin are installed.
```svelte
Slide 1
Slide 2
Slide 3
```
--------------------------------
### setupLiveRegion
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/accessibility/__next.docs.$oc$slug.__PAGE__.txt
Sets up a live region for accessibility, which announces carousel slide changes to screen readers. It accepts an HTML element or a selector string for the live region container.
```APIDOC
## setupLiveRegion
### Description
Sets up a live region for accessibility, which announces carousel slide changes to screen readers. It accepts an HTML element or a selector string for the live region container.
### Method
`emblaApi.plugins().accessibility?.setupLiveRegion(liveRegion)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
emblaApi.plugins().accessibility?.setupLiveRegion('#embla-live-region')
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Install Wheel Gestures Plugin via pnpm
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/plugins/wheel-gestures/__next.docs.$oc$slug.__PAGE__.txt
Install the Wheel Gestures plugin using pnpm for your project.
```shell
pnpm add embla-carousel-wheel-gestures
```
--------------------------------
### Add Previous/Next Buttons with React
Source: https://github.com/davidjerleke/embla-carousel/blob/master/docs/docs/guides/previous-and-next-buttons/__next.docs.$oc$slug.__PAGE__.txt
Implement previous and next navigation buttons in a React application using the `embla-carousel-react` hook. This example shows how to use `useEmblaCarousel` to get the API instance and attach click handlers.
```jsx
import React from 'react'
import useEmblaCarousel from 'embla-carousel-react'
export function EmblaCarousel() {
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false })
const goToPrev = () => emblaApi?.goToPrev()
const goToNext = () => emblaApi?.goToNext()
return (