### AlpineJS Component Slider NPM Setup Source: https://context7.com/fylgja/snap-slider/llms.txt Illustrates how to set up the Fylgja Snap Slider AlpineJS plugin when using NPM. This involves importing AlpineJS and the snap-slider plugin, registering the plugin, and starting AlpineJS. ```javascript // NPM Installation with AlpineJS import Alpine from 'alpinejs'; import snapSlider from '@fylgja/snap-slider/alpine'; window.Alpine = Alpine; Alpine.plugin(snapSlider); Alpine.start(); ``` -------------------------------- ### Install Snap Slider via NPM Source: https://github.com/fylgja/snap-slider/blob/main/README.md Installs the Fylgja Snap Slider package using npm. This is the recommended method for integrating into modern JavaScript projects. ```sh npm install @fylgja/snap-slider ``` -------------------------------- ### Initialize, Destroy, and Refresh Snap Slider Source: https://github.com/fylgja/snap-slider/blob/main/README.md Demonstrates the core methods for managing the Snap Slider's lifecycle. 'init()' starts the slider (usually automatic), 'destroy()' cleans up event listeners, and 'refreshSlides()' is for dynamic content changes. ```javascript // Assuming snapSliderInstance is obtained as shown above snapSliderInstance.init(); // Typically called automatically snapSliderInstance.destroy(); snapSliderInstance.refreshSlides(); ``` -------------------------------- ### Alpine.js Snap Slider Directive Source: https://github.com/fylgja/snap-slider/blob/main/alpinejs.html This example demonstrates how to initialize the x-snap-slider Alpine.js plugin. It shows the basic integration by adding the 'x-snap-slider' directive to a scrollable container. Ensure the Alpine.js library is included in your project. ```html
``` -------------------------------- ### JavaScript API for Slider Instance Access Source: https://context7.com/fylgja/snap-slider/llms.txt Provides examples of how to obtain the SnapSlider class instance from both standard custom elements and Alpine.js components. It includes a check to ensure the slider has initialized correctly, outputting to the console. ```javascript // For Custom Element const snapSliderElement = document.querySelector('snap-slider'); const sliderInstance = snapSliderElement.slider; // For AlpineJS Component const alpineSliderElement = document.querySelector('[x-snap-slider]'); const sliderInstance = alpineSliderElement.snapSlider; // Check if slider initialized successfully if (sliderInstance) { console.log('Slider initialized with', sliderInstance.slides.length, 'slides'); } else { console.error('Slider failed to initialize - check for [data-track] element'); } ``` -------------------------------- ### JavaScript API - Event Handling Source: https://context7.com/fylgja/snap-slider/llms.txt This section details how to subscribe to the `slideChange` event to react to viewport changes and update the UI based on the slider's state. It provides an example of accessing event details like visible slides, slider position, and overflow status. ```APIDOC ## JavaScript API - Event Handling ### Description Listen to the `slideChange` event to update your UI based on the slider's current state. ### Method `addEventListener` ### Event Name `slideChange` ### Event Detail Properties - **inViewSlides** (Array) - Array of HTML elements currently visible in the viewport. - **totalInViewSlides** (Number) - The total number of slides currently visible. - **firstInViewSlide** (HTMLElement) - The first slide element that is currently visible. - **lastInViewSlide** (HTMLElement) - The last slide element that is currently visible. - **isAtStart** (Boolean) - True if the slider is currently at the beginning. - **isAtEnd** (Boolean) - True if the slider is currently at the end. - **hasNoOverflow** (Boolean) - True if all slides are visible and no scrolling is needed. ### Request Example ```javascript const sliderEl = document.querySelector('snap-slider'); sliderEl.addEventListener('slideChange', (event) => { const { inViewSlides, totalInViewSlides, firstInViewSlide, lastInViewSlide, isAtStart, isAtEnd, hasNoOverflow } = event.detail; console.log(`Viewing ${totalInViewSlides} slide(s)`); if (isAtStart) { console.log('At the beginning of the slider'); } if (isAtEnd) { console.log('At the end of the slider'); } if (hasNoOverflow) { console.log('All slides are visible - no scrolling needed'); } const slideCounter = document.getElementById('slide-counter'); if (slideCounter && firstInViewSlide) { const currentIndex = Array.from(inViewSlides[0].parentElement.children).indexOf(firstInViewSlide); slideCounter.textContent = `Slide ${currentIndex + 1}`; } }); ``` ### Response N/A (This is an event listener) ``` -------------------------------- ### Get Snap Slider Instance (Alpine.js) Source: https://github.com/fylgja/snap-slider/blob/main/README.md Retrieves the Snap Slider instance from an Alpine.js component. This method is used when integrating the slider with Alpine.js directives. ```javascript const sliderEl = document.querySelector('[x-snap-slider]'); const snapSliderInstance = sliderEl.snapSlider; ``` -------------------------------- ### Snap Slider JavaScript API Source: https://github.com/fylgja/snap-slider/blob/main/README.md This section details the methods and events available for interacting with the Snap Slider programmatically. You can get the slider instance from custom elements or Alpine.js components and use methods like `init()`, `destroy()`, and `refreshSlides()`. The slider also emits a `slideChange` event with detailed information about the current view. ```APIDOC ## Snap Slider JavaScript API ### Methods To interact with the slider programmatically, first obtain the `SnapSlider` instance. **For Custom Elements:** ```javascript const snapSliderElement = document.querySelector('snap-slider'); const snapSliderInstance = snapSliderElement.slider; ``` **For Alpine.js Components:** ```javascript const sliderEl = document.querySelector('[x-snap-slider]'); const snapSliderInstance = sliderEl.snapSlider; ``` #### Available Methods - **`init()`**: Initializes the slider. This method is typically called automatically on element creation. - **`destroy()`**: Removes all event listeners and observers associated with the slider. - **`refreshSlides()`**: Re-initializes the slider. This is useful when slides are added or removed dynamically after the initial setup. ### Events The slider dispatches a custom event named `slideChange` on the slider element whenever the set of slides currently in view changes. #### Listening to `slideChange` Event ```javascript const sliderEl = document.querySelector('snap-slider'); // Or '[x-snap-slider]' sliderEl.addEventListener('slideChange', (event) => { console.log(event.detail); }); ``` #### `event.detail` Object Properties - **`inViewSlides`** (Array) - An array containing the slide elements that are currently visible. - **`totalInViewSlides`** (Number) - The total count of slides currently in view. - **`firstInViewSlide`** (Element) - The first slide element that is visible. - **`lastInViewSlide`** (Element) - The last slide element that is visible. - **`isAtStart`** (Boolean) - Indicates whether the slider is currently positioned at the beginning. - **`isAtEnd`** (Boolean) - Indicates whether the slider is currently positioned at the end. - **`hasNoOverflow`** (Boolean) - Indicates whether all slides are visible simultaneously without overflow. ``` -------------------------------- ### Get Snap Slider Instance (Custom Element) Source: https://github.com/fylgja/snap-slider/blob/main/README.md Retrieves the Snap Slider instance from a custom HTML element. This is the primary way to interact with the slider programmatically when using the custom element. ```javascript const snapSliderElement = document.querySelector('snap-slider'); const snapSliderInstance = snapSliderElement.slider; ``` -------------------------------- ### AlpineJS Component Slider Integration Source: https://context7.com/fylgja/snap-slider/llms.txt Integrates Fylgja Snap Slider with AlpineJS using a custom directive `x-snap-slider`. This example includes navigation buttons and auto-pagination configured via modifiers. Requires AlpineJS and the Snap Slider Alpine plugin to be loaded. ```html
Photo 1 Photo 2 Photo 3
``` -------------------------------- ### Instantiate SnapSlider Class - JavaScript Source: https://context7.com/fylgja/snap-slider/llms.txt Demonstrates how to instantiate the SnapSlider class directly in JavaScript. This allows for explicit control over the slider's initialization and configuration. It covers basic instantiation with a slider element, advanced configuration options, and accessing the slider's properties after instantiation. No external dependencies are required for this basic usage. ```javascript import { SnapSlider } from '@fylgja/snap-slider'; // Basic instantiation const sliderElement = document.getElementById('my-slider'); const slider = new SnapSlider(sliderElement); // With configuration options const sliderWithOptions = new SnapSlider(sliderElement, { labelSepparator: '|', // Changes "1 of 5" to "1 | 5" autoPager: true, // Generate pagination automatically groupPager: true // Group pagers for multi-slide views }); // Access slider properties console.log('Total slides:', slider.slides.length); console.log('Track element:', slider.track); console.log('Pager element:', slider.pager); console.log('Navigation buttons:', slider.navBtns); ``` -------------------------------- ### HTML for Custom Manual Pagination Source: https://context7.com/fylgja/snap-slider/llms.txt Demonstrates creating a custom pagination layout using HTML buttons linked to slide IDs. This method allows full control over the pager's appearance and behavior, leveraging ARIA attributes for accessibility. ```html

Introduction

Welcome to our product showcase

Features

Explore our amazing features

Pricing

Choose the plan that fits you

``` -------------------------------- ### Custom Configuration Options Source: https://context7.com/fylgja/snap-slider/llms.txt Learn how to customize the Snap Slider's appearance and behavior using various data attributes. This includes options for pagination, labels, and CSS classes for elements like the pager and markers. ```APIDOC ## Custom Configuration Options ### Description Customize the appearance and functionality of the Snap Slider using data attributes directly on the `snap-slider` element. ### Data Attributes - **`aria-label`** (String) - Sets the ARIA label for the slider component. - **`data-auto-pager`** (Boolean) - Enables or disables the automatic generation of pagination indicators. Defaults to `false`. - **`data-group-pager`** (Boolean) - Groups pagination indicators if set to `true`. Defaults to `false`. - **`data-slide-label-sepparator`** (String) - The separator character used in slide labels (e.g., "/"). - **`data-pager-class`** (String) - CSS class to apply to the automatically generated pager container. - **`data-marker-class`** (String) - CSS class to apply to each pagination marker (dot). - **`data-prev`** - Attribute to mark a button element as the previous slide navigation. - **`data-next`** - Attribute to mark a button element as the next slide navigation. ### HTML Example ```html
Product 1 Product 2 Product 3
``` ### Notes - Slides will automatically receive ARIA labels like "1 / 3" based on their position and the total number of slides, using the `data-slide-label-sepparator`. - The slider ID (e.g., "product-showcase") is used for generating unique IDs for elements like the pager. - Navigation buttons marked with `data-prev` and `data-next` will be automatically wired up if present. ``` -------------------------------- ### Configure Custom Pager with Slide Links Source: https://github.com/fylgja/snap-slider/blob/main/README.md Illustrates how to set up a custom pager for the Snap Slider. Each pager marker links to a specific slide using `href` or `data-target-id`, requiring slides to have unique IDs. ```html Slide 1 ``` -------------------------------- ### HTML for Grouped Pagination Source: https://context7.com/fylgja/snap-slider/llms.txt Illustrates how to configure Snap Slider for grouped pagination, suitable for scenarios where multiple slides are visible at once. The `data-group-pager` attribute, combined with CSS Grid for track layout, enables this functionality. ```html
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
Item 7
Item 8
Item 9
``` -------------------------------- ### Dynamic Slide Management Source: https://context7.com/fylgja/snap-slider/llms.txt This section demonstrates how to dynamically add and remove slides from the `snap-slider`. It highlights that the slider automatically refreshes its state and management when slides are modified, thanks to a `MutationObserver`. ```APIDOC ## Dynamic Slide Management ### Description Manage your slides dynamically by adding or removing them from the slider. The component automatically observes changes and updates its internal state. ### Method DOM Manipulation (appendChild, removeChild) ### Usage Add or remove slide elements within the slider's track element. The slider will automatically detect these changes. ### HTML Example ```html
Slide 1
Slide 2
``` ### JavaScript Example ```javascript const slider = document.getElementById('dynamic-slider'); const track = slider.querySelector('[data-track]'); let slideCount = 2; document.getElementById('add-slide').addEventListener('click', () => { slideCount++; const newSlide = document.createElement('div'); newSlide.style.cssText = 'scroll-snap-align: start; flex: 0 0 300px; background: #ccc; padding: 2rem;'; newSlide.textContent = `Slide ${slideCount}`; track.appendChild(newSlide); // Slider automatically refreshes via MutationObserver }); document.getElementById('remove-slide').addEventListener('click', () => { const lastSlide = track.lastElementChild; if (lastSlide && track.children.length > 1) { lastSlide.remove(); slideCount--; // Slider automatically refreshes via MutationObserver } }); ``` ### Response N/A (This is a demonstration of DOM manipulation and automatic slider updates) ``` -------------------------------- ### Custom Element Slider with Navigation and Auto Pagination Source: https://context7.com/fylgja/snap-slider/llms.txt Shows how to implement a Fylgja Snap Slider Custom Element with navigation buttons and automatic pagination. The component generates pagination markers and handles their states. Uses data attributes for configuration and includes basic styling for controls and markers. ```html

Slide 1

First slide content

Slide 2

Second slide content

Slide 3

Third slide content

``` -------------------------------- ### JavaScript API for Programmatic Slider Control Source: https://context7.com/fylgja/snap-slider/llms.txt Demonstrates using the SnapSlider instance's methods to control the slider programmatically. This includes navigating slides, refreshing the slider after DOM changes, and initializing or destroying the slider instance. ```javascript const sliderEl = document.querySelector('snap-slider'); const slider = sliderEl.slider; // Navigate to next slide slider.goToSlideDir('next'); // Navigate to previous slide slider.goToSlideDir('prev'); // Refresh slides after dynamically adding/removing const track = sliderEl.querySelector('[data-track]'); const newSlide = document.createElement('div'); newSlide.innerHTML = '

New Slide

Dynamically added

'; track.appendChild(newSlide); slider.refreshSlides(); // Re-initializes slider with new slides // Destroy slider (removes all observers and event listeners) slider.destroy(); // Reinitialize slider slider.init(); ``` -------------------------------- ### Enable Auto Pager and Group Pager in Alpine.js Source: https://github.com/fylgja/snap-slider/blob/main/README.md Configures the Snap Slider in Alpine.js to automatically generate pagination markers and group them based on visible slides by using directive modifiers. ```html
...
``` -------------------------------- ### Basic Custom Element Slider Source: https://context7.com/fylgja/snap-slider/llms.txt Demonstrates the basic integration of Fylgja Snap Slider as a Custom Element. Requires importing the custom element script and defining a track container with slides. CSS is used to enable scroll snapping. ```html
Slide 1 Slide 2 Slide 3 Slide 4
``` -------------------------------- ### Configure Snap Slider with Data Attributes in HTML Source: https://context7.com/fylgja/snap-slider/llms.txt Customize the Snap Slider's appearance and behavior using data attributes directly in the HTML. Options include pagination generation, custom classes for pagers and markers, and accessibility labels. ```html
Product 1 Product 2 Product 3
``` -------------------------------- ### Use Snap Slider Custom Element in HTML Source: https://github.com/fylgja/snap-slider/blob/main/README.md Demonstrates the basic structure for using the Snap Slider as a Custom Element in HTML. It requires a `` tag with a child `[data-track]` element for the slides. ```html
``` -------------------------------- ### Add and Remove Slides Dynamically with HTML and JavaScript Source: https://context7.com/fylgja/snap-slider/llms.txt Manage dynamic content by adding or removing slides to the slider. The component automatically refreshes its state due to a MutationObserver, ensuring seamless integration of new or removed slides without manual reinitialization. ```html
Slide 1
Slide 2
``` ```javascript const slider = document.getElementById('dynamic-slider'); const track = slider.querySelector('[data-track]'); let slideCount = 2; document.getElementById('add-slide').addEventListener('click', () => { slideCount++; const newSlide = document.createElement('div'); newSlide.style.cssText = 'scroll-snap-align: start; flex: 0 0 300px; background: #ccc; padding: 2rem;'; newSlide.textContent = `Slide ${slideCount}`; track.appendChild(newSlide); }); document.getElementById('remove-slide').addEventListener('click', () => { const lastSlide = track.lastElementChild; if (lastSlide && track.children.length > 1) { lastSlide.remove(); slideCount--; } }); ``` -------------------------------- ### Include Snap Slider Alpine.js Version via CDN Source: https://github.com/fylgja/snap-slider/blob/main/README.md Integrates the Snap Slider for Alpine.js into an HTML document using a CDN link. This is for projects utilizing Alpine.js for their frontend interactivity. ```html ``` -------------------------------- ### Include Snap Slider Custom Element via CDN Source: https://github.com/fylgja/snap-slider/blob/main/README.md Integrates the Snap Slider Custom Element into an HTML document using a CDN link. This method is suitable for projects that do not use a build process. ```html ``` -------------------------------- ### Import and Register Snap Slider Alpine.js Component Source: https://github.com/fylgja/snap-slider/blob/main/README.md Imports the Alpine.js plugin for Snap Slider and registers it with Alpine.js. This enables the use of the `x-snap-slider` directive. ```javascript import Alpine from 'alpinejs'; import snapSlider from '@fylgja/snap-slider/alpine'; window.Alpine = Alpine; Alpine.plugin(snapSlider); Alpine.start(); ``` -------------------------------- ### Snap Slider Custom Element Integration - HTML Source: https://github.com/fylgja/snap-slider/blob/main/index.html This HTML snippet demonstrates how to include the Fylgja Snap Slider custom element in a web page. It uses a script tag to load the component from a CDN and includes placeholder images within a `snap-slider` element. The `defer` attribute ensures the script executes after the HTML is parsed. ```html ``` -------------------------------- ### Listen to Slide Change Events in JavaScript Source: https://context7.com/fylgja/snap-slider/llms.txt Subscribe to the `slideChange` event to react to viewport changes. This event provides details about the currently visible slides, such as their count, elements, and position within the slider. It's useful for updating UI elements based on the slider's state. ```javascript const sliderEl = document.querySelector('snap-slider'); sliderEl.addEventListener('slideChange', (event) => { const { inViewSlides, totalInViewSlides, firstInViewSlide, lastInViewSlide, isAtStart, isAtEnd, hasNoOverflow } = event.detail; console.log(`Viewing ${totalInViewSlides} slide(s)`); if (isAtStart) { console.log('At the beginning of the slider'); } if (isAtEnd) { console.log('At the end of the slider'); } if (hasNoOverflow) { console.log('All slides are visible - no scrolling needed'); } const slideCounter = document.getElementById('slide-counter'); if (slideCounter && firstInViewSlide) { const currentIndex = Array.from(inViewSlides[0].parentElement.children).indexOf(firstInViewSlide); slideCounter.textContent = `Slide ${currentIndex + 1}`; } }); ``` -------------------------------- ### Use Snap Slider with Alpine.js Directive Source: https://github.com/fylgja/snap-slider/blob/main/README.md Applies the `x-snap-slider` directive to an element in Alpine.js to enable the Snap Slider functionality. It requires a `[data-track]` element for the slides. ```html
``` -------------------------------- ### Listen for Snap Slider 'slideChange' Event Source: https://github.com/fylgja/snap-slider/blob/main/README.md Attaches an event listener to detect when the visible slides in the Snap Slider change. The event detail provides comprehensive information about the current slide state. ```javascript const sliderEl = document.querySelector('snap-slider'); // Or '[x-snap-slider]' sliderEl.addEventListener('slideChange', (event) => { console.log(event.detail); // event.detail contains properties like inViewSlides, totalInViewSlides, etc. }); ``` -------------------------------- ### Import Snap Slider Custom Element Source: https://github.com/fylgja/snap-slider/blob/main/README.md Imports the Snap Slider Custom Element definition into a JavaScript module. This allows the `` tag to be recognized and used in the HTML. ```javascript import '@fylgja/snap-slider/custom-element'; ``` -------------------------------- ### Snap Pager and Snap Marker CSS Source: https://github.com/fylgja/snap-slider/blob/main/alpinejs.html These CSS rules define the styling for the snap slider's pagination controls. '.snap-pager' styles the container for pagination dots, ensuring they are centered and scrollable. '.snap-marker' styles individual pagination dots, including active states and transitions. ```css .snap-pager { justify-content: center; display: flex; overflow: auto; margin-block: 1rem; gap: 0.5em; min-block-size: 1em; } .snap-marker { --btn-active-stroke: var(--brand); --btn-active-bg: var(--brand); padding: 2px; width: 1em; height: 1em; transition: color 0.2s, background-color 0.2s, border-color 0.2s, box-shadow 0.2s, var(--outline-transition), width 0.2s; } .snap-marker[aria-current="true"] { width: 1.5em; } ``` -------------------------------- ### Add Slide with JavaScript Source: https://github.com/fylgja/snap-slider/blob/main/alpinejs.html This JavaScript snippet adds a new image slide to a target element when an attribute 'data-action-add-slide' is clicked. It randomly selects an image from a predefined array and appends it as an 'img' element. It requires a target element with a 'data-track' attribute to append the new slide. ```javascript document.addEventListener("click", (e) => { const triggerName = "data-action-add-slide"; if (!e.target.hasAttribute(triggerName)) return; const triggerTarget = e.target.getAttribute(triggerName); const target = document .getElementById(triggerTarget) ?.querySelector("[data-track]"); if (!target) return; const newSlide = document.createElement("img"); const imgArray = [ "seagull", "hare", "bear", "fox", "frog", "cat", "dog", ]; const imgArrayRandom = Math.floor( Math.random() * imgArray.length ); newSlide.setAttribute( "src", `https://fylgja.dev/images/placeholders/${imgArray[imgArrayRandom]}.webp` ); newSlide.setAttribute("alt", "JS Slide"); newSlide.setAttribute("width", "480"); newSlide.setAttribute("height", "320"); target.appendChild(newSlide); }); ``` -------------------------------- ### Snap Slider CSS Styling - CSS Source: https://github.com/fylgja/snap-slider/blob/main/index.html This CSS defines styles for the snap slider's pager and marker elements. It includes properties for layout, appearance, and transitions. The `.snap-marker` styles adapt when its `aria-current` attribute is true, indicating the active slide. ```css .snap-pager { justify-content: center; display: flex; overflow: auto; margin-block: 1rem; gap: 0.5em; min-block-size: 1em; } .snap-marker { --btn-active-stroke: var(--brand); --btn-active-bg: var(--brand); padding: 2px; width: 1em; height: 1em; transition: color 0.2s, background-color 0.2s, border-color 0.2s, box-shadow 0.2s, var(--outline-transition), width 0.2s; } .snap-marker[aria-current="true"] { width: 1.5em; } ``` -------------------------------- ### Add Slide Button Functionality - JavaScript Source: https://github.com/fylgja/snap-slider/blob/main/index.html This JavaScript code snippet adds functionality to a button that, when clicked, appends a new image slide to a target element. It selects an image randomly from a predefined array and sets its source and alt attributes. This requires an HTML structure with elements having specific data attributes for triggering and targeting. ```javascript document.addEventListener("click", (e) => { const triggerName = "data-action-add-slide"; if (!e.target.hasAttribute(triggerName)) return; const triggerTarget = e.target.getAttribute(triggerName); const target = document .getElementById(triggerTarget) ?.querySelector("[data-track]"); if (!target) return; const newSlide = document.createElement("img"); const imgArray = [ "seagull", "hare", "bear", "fox", "frog", "cat", "dog", ]; const imgArrayRandom = Math.floor( Math.random() * imgArray.length ); newSlide.setAttribute( "src", `https://fylgja.dev/images/placeholders/${imgArray[imgArrayRandom]}.webp` ); newSlide.setAttribute("alt", "JS Slide"); newSlide.setAttribute("width", "480"); newSlide.setAttribute("height", "320"); target.appendChild(newSlide); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.