### Installation & Import Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Shows how to install and import keen-slider for various environments. ```javascript // NPM npm install keen-slider // Browser // ES6 modules import KeenSlider from 'keen-slider' // CommonJS const KeenSlider = require('keen-slider').default // React import { useKeenSlider } from 'keen-slider/react' // Vue 3 import { useKeenSlider } from 'keen-slider/vue' // React Native import { useKeenSliderNative } from 'keen-slider/react-native' ``` -------------------------------- ### Responsive Patterns - Breakpoints Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Example configuration for responsive slides per view using breakpoints. ```typescript { slides: { perView: 1 }, breakpoints: { '(min-width: 480px)': { slides: { perView: 2 } }, '(min-width: 768px)': { slides: { perView: 3 } }, } } ``` -------------------------------- ### Custom rendering Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Example of using custom rendering mode and handling slide transformations and opacity. ```typescript const slider = new KeenSlider(container, { renderMode: 'custom' }) slider.on('detailsChanged', (instance) => { instance.slides.forEach((slide, idx) => { const d = instance.track.details.slides[idx] const offset = d.distance * instance.size slide.style.transform = `translateX(${offset}px)` slide.style.opacity = d.portion.toString() }) }) ``` -------------------------------- ### Virtualize large lists Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Hint for virtualizing large lists, with a React example using `react-window`. ```typescript // React example with virtualization import { FixedSizeList } from 'react-window' ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md A comprehensive example demonstrating various configuration options for Keen Slider. ```typescript const slider = new KeenSlider( '.carousel', { // Core initial: 0, loop: true, range: { min: 0, max: 10 }, rtl: false, defaultAnimation: { duration: 600, easing: (t) => 1 + --t * t * t * t * t, }, // Web/DOM disabled: false, selector: '.slide', slides: { number: null, perView: 3, spacing: 20, origin: 'center', }, vertical: false, breakpoints: { '(max-width: 768px)': { slides: { perView: 1, spacing: 10 }, }, }, // Drag drag: true, dragSpeed: 1, rubberband: true, // Animation mode: 'snap', // Rendering renderMode: 'precision', // Hooks created: (instance) => { console.log('Slider created') }, slideChanged: (instance) => { console.log('Slide:', instance.track.details?.abs) }, }, [customPlugin] ) ``` -------------------------------- ### TypeScript Usage Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Basic TypeScript setup for Keen Slider, including instance type and event handling. ```typescript import KeenSlider, { KeenSliderInstance } from 'keen-slider' let slider: KeenSliderInstance slider = new KeenSlider('.carousel', { loop: true, }) slider.on('slideChanged', (instance) => { console.log(instance.track.details?.abs) }) ``` -------------------------------- ### next Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Example for using the next method. ```typescript slider.next(); ``` -------------------------------- ### dragStarted Hook Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of listening to the 'dragStarted' event. ```typescript slider.on('dragStarted', (instance) => { console.log('Drag started at position:', instance.track.details.position) }) ``` -------------------------------- ### Initial Slide Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Starting slide index. ```typescript new KeenSlider(container, { initial: 2, // Start at 3rd slide }) ``` -------------------------------- ### prev Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Example for using the prev method. ```typescript slider.prev(); ``` -------------------------------- ### Keen Slider Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md An example of creating and using a plugin with Keen Slider, including listening to the 'created' event. ```javascript var slider = new KeenSlider( '#my-slider', { loop: true, }, [ slider => { slider.on('created', () => { alert('Hello World') }) }, ] ) ``` -------------------------------- ### Usage Example - Listen for animationStarted hook Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of logging the target slide index when an animation starts. ```typescript slider.on('animationStarted', (instance) => { console.log('Animating to slide:', instance.animator.targetIdx); }); ``` -------------------------------- ### dragged Hook Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of listening to the 'dragged' event. ```typescript slider.on('dragged', (instance) => { const position = instance.track.details.position console.log('Dragging at position:', position) }) ``` -------------------------------- ### moveToIdx Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Examples demonstrating how to use the moveToIdx method with different parameters. ```typescript // Move to slide 3 (absolute index) slider.moveToIdx(3, true); // Move to slide 1 relative to current position slider.moveToIdx(1, false); // Custom animation timing slider.moveToIdx(2, true, { duration: 1000, easing: t => 1 + --t * t * t * t * t // Quint easing }); ``` -------------------------------- ### Animator start keyframes Source: https://github.com/rcbyr/keen-slider/blob/master/docs/react-native.md Example of how to start a new animation with keyframes using the animator module. ```typescript slider.animator.start([keyframe1, keyframe2]) ``` -------------------------------- ### Manual Rendering Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example demonstrating manual DOM updates in custom render mode using the 'detailsChanged' hook. ```typescript const slider = new KeenSlider(container, { renderMode: 'custom' }) slider.on('detailsChanged', (instance) => { // Manually update DOM based on track details const details = instance.track.details instance.slides.forEach((slide, idx) => { const slideDetails = details.slides[idx] const offset = slideDetails.distance * instance.size slide.style.transform = `translateX(${offset}px)` }) }) ``` -------------------------------- ### TrackInstance Interface - init Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the init method. ```typescript slider.track.init(0); // Reset to first slide slider.track.init(2); // Initialize at slide 2 ``` -------------------------------- ### Container Sizing with getBoundingClientRect Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of using `getBoundingClientRect()` to get accurate container sizing. ```typescript const rect = container.getBoundingClientRect() const size = rect.width // or rect.height for vertical ``` -------------------------------- ### Breakpoints Configuration Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of configuring responsive options using media queries. ```typescript { breakpoints: { '(min-width: 768px)': { slides: { perView: 3, spacing: 10 }, }, '(min-width: 1024px)': { slides: { perView: 4, spacing: 15 }, }, } } ``` -------------------------------- ### Accessing the container size Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of how to get the width or height of the container in pixels. ```typescript const containerSize: number = slider.size ``` -------------------------------- ### Real-World Example: Thumbnail Plugin Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md A comprehensive example of a thumbnail plugin for Keen Slider, including event handling, state management, and exposing custom methods. ```typescript interface ThumbnailContext { selectThumbnail: (idx: number) => void } const thumbnailPlugin: KeenSliderPlugin<{}, ThumbnailContext> = ( slider ) => { let thumbnails: HTMLElement[] = [] slider.on('created', (instance) => { // Find thumbnail elements const container = instance.container thumbnails = Array.from( container.querySelectorAll('[data-thumbnail]') ) as HTMLElement[] // Click handlers thumbnails.forEach((thumb, idx) => { thumb.addEventListener('click', () => { instance.moveToIdx(idx, true) }) }) // Highlight initial thumbnail updateActiveThumbnail(0) }) slider.on('slideChanged', (instance) => { updateActiveThumbnail(instance.track.details?.abs ?? 0) }) const updateActiveThumbnail = (idx: number) => { thumbnails.forEach((thumb, i) => { thumb.classList.toggle('active', i === idx) }) } // Expose method slider.selectThumbnail = (idx: number) => { slider.moveToIdx(idx, true) } slider.on('destroyed', () => { thumbnails.forEach((thumb) => { thumb.removeEventListener('click', () => {}) }) thumbnails = [] }) } ``` -------------------------------- ### Installation with npm Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Install Keen Slider using npm. ```bash npm install keen-slider ``` -------------------------------- ### Updating and moving to a specific slide example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of updating slider options and moving to a specific slide index. ```typescript // Update and move to specific slide slider.update({ loop: false }, 0) ``` -------------------------------- ### Animator Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Starting and stopping animations using the animator with keyframes and easing functions. ```typescript slider.animator.start([ { distance: 100, duration: 500, easing: t => 1 + --t * t * t * t * t } ]) slider.animator.stop() ``` -------------------------------- ### on Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Examples showing how to listen for and remove event listeners using the on method. ```typescript // Listen for slide changes slider.on('slideChanged', (instance) => { console.log('Current slide:', instance.track.details.abs); }); // Listen for drag end slider.on('dragEnded', (instance) => { console.log('Drag ended at position:', instance.track.details.position); }); // Remove listener const callback = (s) => { /* ... */ }; slider.on('created', callback); slider.on('created', callback, true); // Remove listener ``` -------------------------------- ### Auto-play Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md A plugin that automatically advances slides at a set interval and provides methods to start and stop the autoplay. ```typescript const autoPlayPlugin = (slider) => { let autoplayId = null const start = () => { autoplayId = setInterval(() => { slider.next() }, 3000) // 3 seconds } const stop = () => { clearInterval(autoplayId) } slider.on('created', start) slider.on('dragStarted', stop) slider.on('dragEnded', start) slider.on('destroyed', stop) // Expose control methods slider.autoplay = { start, stop } } // Usage const slider = new KeenSlider(container, {}, [autoPlayPlugin]) slider.autoplay.stop() ``` -------------------------------- ### emit Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Examples for manually emitting hook events. ```typescript slider.emit('created'); slider.emit('slideChanged'); ``` -------------------------------- ### Testing Plugins Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md An example of how to test Keen Slider plugins using a testing framework like Jest, including setup, teardown, and assertion of plugin behavior. ```typescript describe('MyPlugin', () => { let slider: KeenSliderInstance let container: HTMLElement beforeEach(() => { container = document.createElement('div') container.innerHTML = '
1
2
3
' document.body.appendChild(container) slider = new KeenSlider( container.querySelector('.keen-slider'), {}, [myPlugin] ) }) afterEach(() => { slider?.destroy() document.body.removeChild(container) }) it('should initialize correctly', () => { expect(slider.myProperty).toBeDefined() }) it('should respond to slide changes', (done) => { slider.on('slideChanged', () => { expect(slider.stats.slideChanges).toBe(1) done() }) slider.next() }) }) ``` -------------------------------- ### React Props Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Example of using React state and effects to manage slider properties like `perView` based on window size. ```typescript const [perView, setPerView] = useState(1) const [ref, slider] = useKeenSlider({ slides: { perView } }) useEffect(() => { const handleResize = () => { setPerView(window.innerWidth > 768 ? 3 : 1) } window.addEventListener('resize', handleResize) return () => window.removeEventListener('resize', handleResize) }, []) ``` -------------------------------- ### Plugin Ordering Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Demonstrates how plugins are executed in order and how later plugins can depend on earlier ones. ```typescript const slider = new KeenSlider( container, options, [ plugin1, // Executed first plugin2, // Can rely on plugin1 plugin3, // Can rely on plugin1 and plugin2 ] ) ``` -------------------------------- ### Update Configuration - With Slide Navigation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of updating options and moving to a specific slide. ```typescript // Update and move to slide slider.update({ loop: false }, 0) ``` -------------------------------- ### Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md An example demonstrating how to access and use the track details within a 'detailsChanged' event listener. ```typescript slider.on('detailsChanged', (instance) => { const details = instance.track.details; console.log('Active slide:', details.abs); console.log('Position:', details.position); console.log('Progress:', details.progress); console.log('Visible slides:', details.slides.filter(s => s.portion > 0) ); }); ``` -------------------------------- ### TrackInstance Interface - to Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the to method. ```typescript slider.track.to(0); // Move to position 0 slider.track.to(100); // Move to position 100 ``` -------------------------------- ### Update Configuration - Multiple Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of updating multiple configuration options at runtime. ```typescript // Update multiple options slider.update({ drag: false, rubberband: false, renderMode: 'performance', }) ``` -------------------------------- ### dragEnded Hook Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of listening to the 'dragEnded' event. ```typescript slider.on('dragEnded', (instance) => { console.log('Drag ended at position:', instance.track.details.position) console.log('Final velocity:', instance.track.velocity()) }) ``` -------------------------------- ### Pre-initialization Validation Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/errors.md Example demonstrating how to perform runtime checks on the container, options, and plugins before initializing Keen Slider. ```typescript // Check container exists const container = document.querySelector('.carousel') if (!container) { console.error('Container not found') process.exit(1) } // Validate options const options = { initial: 0, mode: 'snap', // Verify is valid mode slides: { perView: 3 }, // Verify slide config } // Validate plugins const plugins = [myPlugin] // Verify each is a function plugins.forEach(p => { if (typeof p !== 'function') { throw new Error('Plugin must be a function') } }) // Initialize const slider = new KeenSlider(container, options, plugins) ``` -------------------------------- ### TrackInstance Interface - absToRel Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the absToRel method. ```typescript const relIdx = slider.track.absToRel(5); // Convert index 5 to relative ``` -------------------------------- ### update Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Examples demonstrating how to use the update method to change options or reinitialize the track. ```typescript // Update options slider.update({ mode: 'free-snap', drag: false, }); // Update and move to slide 0 slider.update({ loop: false }, 0); // Just reinitialize track slider.update(); ``` -------------------------------- ### Custom Hooks Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Demonstrates how to define and emit custom hooks within a plugin, and how to listen for them. ```typescript const customHookPlugin = (slider) => { slider.on('created', () => { // Emit custom hook slider.emit('myCustomHook') }) } const slider = new KeenSlider( container, { myCustomHook: (instance) => { console.log('Custom hook fired') } }, [customHookPlugin] ) ``` -------------------------------- ### Documenting Plugins Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Example of JSDoc comments for documenting a plugin, including its purpose, parameters, and usage examples. ```typescript /** * Autoplay plugin for KeenSlider * @param {KeenSliderInstance} slider - Slider instance * @example * const slider = new KeenSlider(container, {}, [autoPlayPlugin]) * slider.autoplay.stop() */ const autoPlayPlugin = (slider) => { // Implementation } ``` -------------------------------- ### destroy Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Example for using the destroy method. ```typescript slider.destroy(); // DOM is restored, events are cleaned up ``` -------------------------------- ### TrackInstance Interface - add Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the add method. ```typescript slider.track.add(0.5); // Move forward by 0.5 units slider.track.add(-0.3); // Move backward by 0.3 units ``` -------------------------------- ### Updating options example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of updating slider options to change mode and disable dragging. ```typescript // Update options slider.update({ mode: 'free-snap', drag: false }) ``` -------------------------------- ### React Native Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/docs/react-native.md An example of creating and using a plugin with Keen Slider in a React Native environment. The plugin listens for the 'created' event and shows an alert. ```typescript const slider = useKeenSliderNative( { slides: 4, }, [ slider => { slider.on('created', () => { alert('Hello World') }) }, ] ) ``` -------------------------------- ### TrackInstance Interface - idxToDist Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the idxToDist method. ```typescript // Distance to slide 3 const dist = slider.track.idxToDist(3, true); // Distance from current position const relDist = slider.track.idxToDist(1); // Distance from specific position const fromDist = slider.track.idxToDist(5, true, 0); ``` -------------------------------- ### dragChecked Hook Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of listening to the 'dragChecked' event. ```typescript slider.on('dragChecked', (instance) => { console.log('Drag validated as swipe') }) ``` -------------------------------- ### TrackInstance Interface - distToIdx Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the distToIdx method. ```typescript const idx = slider.track.distToIdx(100); ``` -------------------------------- ### Navigate Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Examples of navigating slides programmatically. ```typescript slider.next() // Next slide slider.prev() // Previous slide slider.moveToIdx(2) // Jump to slide 2 slider.moveToIdx(2, true, { // Custom animation duration: 800, easing: t => t * t }) ``` -------------------------------- ### Basic CSS Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Core CSS classes and properties for styling Keen Slider. ```css .keen-slider { overflow: hidden; } .keen-slider__slide { /* Position will be set by renderer */ } /* Vertical layout */ .keen-slider[data-keen-slider-v] { display: flex; flex-direction: column; } /* RTL layout */ .keen-slider[data-keen-slider-reverse] { direction: rtl; } /* Disabled state */ .keen-slider[data-keen-slider-disabled] { opacity: 0.5; pointer-events: none; } ``` -------------------------------- ### Velocity Calculation Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of retrieving the swipe velocity after drag ends. ```typescript slider.on('dragEnded', (instance) => { const velocity = instance.track.velocity() console.log('Swipe velocity:', velocity) // Used by free/free-snap modes to calculate inertia }) ``` -------------------------------- ### TrackInstance Interface - velocity Method Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/track.md Usage example for the velocity method. ```typescript const v = slider.track.velocity(); console.log('Current velocity:', v); ``` -------------------------------- ### Core API - Constructor Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Signature for the KeenSlider constructor. ```typescript new KeenSlider(container, options?, plugins?) ``` -------------------------------- ### Drag Plugin Configuration Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of configuring the drag plugin with various options. ```typescript const slider = new KeenSlider(container, { drag: true, // Enable/disable dragging dragSpeed: 1, // Speed multiplier (1-2 typical) rubberband: true, // Bounce at boundaries mode: 'snap', // 'snap', 'free', or 'free-snap' }) ``` -------------------------------- ### Custom Hook Callbacks Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of adding custom hook callbacks directly in options. ```typescript { // Built-in hooks created: (slider) => { console.log('Created') }, slideChanged: (slider) => { console.log('Slide changed') }, dragStarted: (slider) => { console.log('Drag started') }, // Custom hooks (with TypeScript generics) myCustomHook: (slider) => { console.log('Custom hook') }, } ``` -------------------------------- ### Complete Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/react-native.md A full example demonstrating how to implement an image carousel using Keen Slider in a React Native application. ```typescript import { useKeenSliderNative } from 'keen-slider/react-native' import { View, Image, Text, TouchableOpacity, StyleSheet, } from 'react-native' import { useState, useEffect } from 'react' const images = [ require('./image1.jpg'), require('./image2.jpg'), require('./image3.jpg'), ] export function ImageCarousel() { const [currentSlide, setCurrentSlide] = useState(0) const slider = useKeenSliderNative({ initial: 0, loop: true, mode: 'free-snap', drag: true, rubberband: true, slides: { perView: 1, spacing: 10, }, }) useEffect(() => { slider.on('slideChanged', (instance) => { if (instance.track.details) { setCurrentSlide(instance.track.details.abs) } }) }, []) return ( {slider.slidesProps.map((slideProps, idx) => ( ))} {currentSlide + 1} / {images.length} slider.prev()} > ← Previous slider.next()} > Next → ) } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, }, sliderContainer: { height: 300, overflow: 'hidden', borderRadius: 8, }, slide: { justifyContent: 'center', alignItems: 'center', }, image: { width: '100%', height: '100%', resizeMode: 'cover', }, counter: { marginTop: 16, textAlign: 'center', fontSize: 16, }, controls: { flexDirection: 'row', gap: 16, justifyContent: 'center', marginTop: 16, }, button: { paddingHorizontal: 16, paddingVertical: 8, backgroundColor: '#007AFF', borderRadius: 4, }, }) ``` -------------------------------- ### Advanced Example with Controls Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/react-hooks.md An advanced example showing how to implement navigation controls (previous, next, jump) and display the current slide using the useKeenSlider hook. ```typescript import { useKeenSlider } from 'keen-slider/react' import { useState } from 'react' export function ControlledCarousel() { const [ref, slider] = useKeenSlider({ initial: 0, loop: true, mode: 'free-snap', }) const [currentSlide, setCurrentSlide] = useState(0) return (
{['Slide 1', 'Slide 2', 'Slide 3'].map((text) => (
{text}
))}
Slide {currentSlide + 1} {slider.current && ( )}
) } ``` -------------------------------- ### Basic Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md A simple plugin that logs a message to the console when the slider is created. ```typescript const myPlugin = (slider) => { // Initialize when slider is created slider.on('created', () => { console.log('My plugin created') }) } const slider = new KeenSlider(container, {}, [myPlugin]) ``` -------------------------------- ### Listening to Events Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/vue-hooks.md An example showing how to listen to keen-slider events like `slideChanged`, `dragStarted`, and `dragEnded` using the `useKeenSlider` composable. ```javascript import { ref, watch } from 'vue' import { useKeenSlider } from 'keen-slider/vue' const [container, slider] = useKeenSlider({ loop: true, }) const slideInfo = ref(null) const isDragging = ref(false) watch(slider, (newSlider) => { if (!newSlider) return newSlider.on('slideChanged', (instance) => { slideInfo.value = instance.track.details }) newSlider.on('dragStarted', () => { isDragging.value = true }) newSlider.on('dragEnded', () => { isDragging.value = false }) }, { immediate: true }) ``` -------------------------------- ### Usage in React Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md Example of using the useKeenSlider hook in a React component. ```javascript import React from 'react' import 'keen-slider/keen-slider.min.css' import { useKeenSlider } from 'keen-slider/react' // import from 'keen-slider/react.es' for to get an ES module export default () => { const [sliderRef, instanceRef] = useKeenSlider( { slideChanged() { console.log('slide changed') }, }, [ // add plugins here ] ) return (
1
2
3
) } ``` -------------------------------- ### Track Details Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Explains the structure and properties of the `track.details` object. ```typescript const d = slider.track.details d.abs // Absolute slide index d.rel // Relative index (in loop) d.position // Current position d.progress // 0..1 progress d.min // Minimum position d.max // Maximum position d.slides // Array of slide details [i].abs // Absolute index [i].distance // Viewport distance [i].portion // Visible portion (0..1) [i].size // Slide size ``` -------------------------------- ### Usage Example - Single keyframe animation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of starting a single keyframe animation with a Quint easing function. ```typescript slider.animator.start([ { distance: 100, duration: 500, easing: t => 1 + --t * t * t * t * t // Quint easing } ]); ``` -------------------------------- ### GPU Acceleration Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Comparison between using `translate3d()` for GPU acceleration and `left` for CPU-based positioning. ```javascript slide.style.transform = 'translate3d(100px, 0, 0)' // Uses GPU slide.style.left = '100px' // CPU-based ``` -------------------------------- ### Usage Example - Multi-keyframe animation with bounce Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of starting a multi-keyframe animation with different easing functions and an early exit for a bounce effect. ```typescript slider.animator.start([ { distance: 200, duration: 800, easing: t => t * t * (3 - 2 * t), // Smooth easing earlyExit: 400 // Exit early }, { distance: -50, duration: 300, easing: t => 1 - t * t // Decelerate } ]); ``` -------------------------------- ### SSR Proper Pattern Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/errors.md Provides a React/Next.js example of using dynamic imports to ensure Keen Slider is only initialized in the browser. ```typescript // React/Next.js example import dynamic from 'next/dynamic' const SliderComponent = dynamic(() => import('./slider'), { ssr: false // Don't render on server }) export default SliderComponent ``` -------------------------------- ### Usage with Options and Plugins Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/keen-slider.md Example demonstrating how to initialize KeenSlider with custom options and plugins. ```javascript // With options and plugins const slider = new KeenSlider( '.carousel', { mode: 'free-snap', drag: true, rubberband: true, }, [customPlugin] ); ``` -------------------------------- ### Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Creating and using custom plugins to extend Keen Slider's functionality. ```typescript const myPlugin = (slider) => { slider.on('slideChanged', () => { // Custom logic }) } const slider = new KeenSlider(container, options, [myPlugin]) ``` -------------------------------- ### Common Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Provides a comprehensive list of common options for configuring keen-slider. ```typescript { // Core initial: 0, loop: true, range: { min: 0, max: 10 }, rtl: false, defaultAnimation: { duration: 500, easing: t => t }, // Web/DOM selector: '.slide', slides: { perView: 3, spacing: 10 }, vertical: false, disabled: false, breakpoints: { '(min-width: 768px)': { slides: { perView: 2 } }, }, // Drag drag: true, dragSpeed: 1, rubberband: true, // Modes mode: 'snap', // 'snap' | 'free' | 'free-snap' // Rendering renderMode: 'precision', // 'precision' | 'performance' | 'custom' // Hooks created: (instance) => {}, slideChanged: (instance) => {}, } ``` -------------------------------- ### Plugin Hooks - Drag/Touch Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Examples of using plugin hooks for drag and touch events. ```typescript // Drag/touch slider.on('dragStarted', () => { // User started dragging }) slider.on('dragged', () => { // User is dragging }) slider.on('dragEnded', () => { // User released drag }) slider.on('dragChecked', () => { // Drag validated as swipe }) ``` -------------------------------- ### Usage - Initialization Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md Initiate KeenSlider with a container, optional options, event hooks, and plugins. ```javascript var slider = new KeenSlider( '#my-slider', { loop: true, created: () => { console.log('created') }, }, [ // add plugins here ] ) ``` -------------------------------- ### Plugin Initialization on 'created' Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Example of setting up DOM elements and event listeners within a plugin when the slider is created. ```typescript slider.on('created', () => { // Setup DOM, event listeners }) ``` -------------------------------- ### Orientation Change Event Listener Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of an event listener for the window 'orientationchange' event. ```typescript window.addEventListener('orientationchange', () => { // Plugin auto-handles orientation changes // Calls update() and resize fixes }) ``` -------------------------------- ### Hooks Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Registering callback functions for various slider events using the `on` method. ```typescript slider.on('created', callback) slider.on('slideChanged', callback) slider.on('dragStarted', callback) slider.on('dragEnded', callback) slider.on('animationEnded', callback) // ... and many more ``` -------------------------------- ### Rendering Modes Configuration Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example of configuring the renderMode option for the Renderer plugin. ```typescript const slider = new KeenSlider(container, { renderMode: 'precision' // Full precision renderMode: 'performance' // Rounded pixels renderMode: 'custom' // Manual rendering }) ``` -------------------------------- ### Event Flow Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Illustrates the typical sequence of events during a user interaction with the drag plugin. ```text User touches/clicks ↓ dragStarted hook fires ↓ User moves (must be horizontal) ↓ dragChecked hook fires ↓ dragged hook fires (repeatedly during drag) ↓ User releases ↓ dragEnded hook fires ↓ Animation starts (snap/free/free-snap mode) ↓ animationStarted hook fires ↓ animationEnded hook fires ``` -------------------------------- ### Create a Slider Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Examples of creating a KeenSlider instance in Vanilla JS, React, and Vue. ```javascript const slider = new KeenSlider('.carousel', { loop: true, mode: 'snap', }) ``` ```typescript const [ref, slider] = useKeenSlider({ loop: true }) return
``` ```typescript const [container, slider] = useKeenSlider({ loop: true }) ``` -------------------------------- ### Custom Drag Speed Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Examples of setting drag speed using a number or a custom function. ```typescript // 2x faster dragging { dragSpeed: 2 } // Custom function { dragSpeed: (val) => val * 0.5 } // 50% slower ``` -------------------------------- ### Rubberband Effect Configuration Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Example of configuring the rubberband effect with min/max boundaries. ```typescript { rubberband: true, // Enable bounce range: { // Boundaries min: 0, max: 10, } } ``` -------------------------------- ### Update Configuration - Reinitialize Track Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of calling `update()` without arguments to reinitialize the track. ```typescript // Just reinitialize track slider.update() ``` -------------------------------- ### Drag Speed Configuration Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/drag-plugin.md Examples of configuring drag speed with a simple multiplier and a custom function. ```typescript // Simple multiplier { dragSpeed: 1.5 } // 1.5x normal speed // Custom function for non-linear response { dragSpeed: (val) => { // val is the drag distance // return modified distance if (Math.abs(val) < 50) { return val * 0.5 // Slow near center } else { return val * 1.5 // Fast at edges } } } ``` -------------------------------- ### Vue 3 Usage Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md Example of integrating keen-slider into a Vue 3 application using the composition API. ```html ``` -------------------------------- ### Instantiating Keen Slider with Custom Plugins Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Demonstrates how to pass custom plugins as the third parameter when creating a new KeenSlider instance. ```typescript const slider = new KeenSlider(container, options, [customPlugin1, customPlugin2]) ``` -------------------------------- ### Breakpoint System Configuration Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Example configuration for the breakpoint system, defining responsive options per media query. ```typescript const slider = new KeenSlider(container, { slides: { perView: 1, spacing: 10 }, breakpoints: { '(min-width: 480px)': { slides: { perView: 2, spacing: 15 }, }, '(min-width: 768px)': { slides: { perView: 3, spacing: 20 }, }, '(min-width: 1024px)': { slides: { perView: 4, spacing: 30 }, }, } }) ``` -------------------------------- ### Breakpoints Option Example Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md Demonstrates how to use the 'breakpoints' option to dynamically change slider settings based on media queries. ```javascript new KeenSlider('#my-slider', { loop: true, breakpoints: { '(min-width: 500px)': { loop: false, }, }, }) ``` -------------------------------- ### Usage Example - Check active animation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of checking if an animation is currently active. ```typescript if (slider.animator.active) { console.log('Animation in progress'); } else { console.log('No animation'); } ``` -------------------------------- ### Basic Usage - Vanilla JavaScript Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Demonstrates basic usage of keen-slider with vanilla JavaScript, including navigation, listening to events, and cleanup. ```javascript const slider = new KeenSlider('.carousel', { loop: true, mode: 'snap', }) // Navigate slider.next() slider.prev() slider.moveToIdx(2) // Listen slider.on('slideChanged', (instance) => { console.log('Slide:', instance.track.details.abs) }) // Cleanup slider.destroy() ``` -------------------------------- ### Usage Example - Stop animation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of stopping the current animation using the stop method. ```typescript slider.animator.stop(); // Animation stops, emits 'animationStopped' if was animating ``` -------------------------------- ### Keyboard Navigation Plugin Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md A plugin that adds keyboard support for navigating slides using arrow keys. ```typescript const keyboardPlugin = (slider) => { const handleKeyDown = (e) => { if (e.key === 'ArrowLeft') { e.preventDefault() slider.prev() } if (e.key === 'ArrowRight') { e.preventDefault() slider.next() } } slider.on('created', () => { document.addEventListener('keydown', handleKeyDown) }) slider.on('destroyed', () => { document.removeEventListener('keydown', handleKeyDown) }) } ``` -------------------------------- ### Usage - HTML Import Source: https://github.com/rcbyr/keen-slider/blob/master/docs/web.md Insert the library directly into your HTML using UMD bundles. ```html ``` -------------------------------- ### Migration from other carousels Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Mapping common methods and events from Swiper and Slick to Keen Slider equivalents. ```typescript // Swiper → KeenSlider swiper.slideNext() // slider.next() swiper.slidePrev() // slider.prev() swiper.slideToLoop(idx) // slider.moveToIdx(idx, true) swiper.on('slideChange') // slider.on('slideChanged') // Slick → KeenSlider slick.slickNext() // slider.next() slick.slickPrev() // slider.prev() slick.slickGoTo(idx) // slider.moveToIdx(idx) $(slick).on('change') // slider.on('slideChanged') ``` -------------------------------- ### Main Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md All options are passed to the KeenSlider constructor as a plain object. ```typescript const slider = new KeenSlider(container, { // Configuration options here }) ``` -------------------------------- ### AnimatorInstance Interface - start method Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Defines the start method for the AnimatorInstance, which begins an animation with specified keyframes. ```typescript start(keyframes: Keyframe[]): void ``` -------------------------------- ### animator Property Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/slider-instance.md Examples showing how to access animation state and methods via the animator property. ```typescript slider.animator.active; // boolean: true if animation in progress slider.animator.targetIdx; // number | null: target slide index slider.animator.start([keyframes]); // Start animation slider.animator.stop(); // Stop current animation ``` -------------------------------- ### Switch animation mode Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Shows how to switch between different animation modes like 'snap' and 'free' scrolling. ```typescript // Start snappy const slider = new KeenSlider(container, { mode: 'snap' }) // Switch to free scrolling slider.update({ mode: 'free' }) // Then to free-snap slider.update({ mode: 'free-snap' }) ``` -------------------------------- ### Basic Usage with String Selector Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/keen-slider.md Example of initializing KeenSlider using a CSS selector for the container. ```javascript // Basic usage with string selector const slider = new KeenSlider('.keen-slider', { loop: true, mode: 'snap', }); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/react-hooks.md A simple example demonstrating how to use the useKeenSlider hook in a functional React component to create a carousel. ```typescript import { useKeenSlider } from 'keen-slider/react' export function Carousel() { const [ref, slider] = useKeenSlider({ loop: true, mode: 'snap', slides: { perView: 3, spacing: 10, }, }) return (
Slide 1
Slide 2
Slide 3
) } ``` -------------------------------- ### Plugin Hooks - Initialization and Slide Navigation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Examples of using plugin hooks for slider initialization and slide navigation events. ```typescript // Initialization slider.on('created', () => { // Slider fully initialized }) // Slide navigation slider.on('slideChanged', () => { // Active slide index changed }) slider.on('detailsChanged', () => { // Track details updated (position, slides info) }) ``` -------------------------------- ### useKeenSliderNative Hook Usage Example (Basic) Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/react-native.md A basic usage example demonstrating how to use the useKeenSliderNative hook in a React Native Carousel component. ```typescript import { useKeenSliderNative } from 'keen-slider/react-native' import { View, ScrollView } from 'react-native' export function Carousel() { const slider = useKeenSliderNative({ loop: true, mode: 'snap', }) return ( {slider.slidesProps.map((slideProps, idx) => ( {/* Slide content */} ))} ) } ``` -------------------------------- ### Set Render Mode for Performance Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of setting the render mode to 'performance' for better performance on low-end devices. ```typescript { renderMode: 'performance' } ``` -------------------------------- ### Disable Dragging Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of disabling mouse and touch dragging. ```typescript { drag: false } ``` -------------------------------- ### Easing Functions - Linear Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/animator.md Example of a linear easing function. ```typescript // Linear (no easing) easing: t => t ``` -------------------------------- ### Reactive Options Example Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/vue-hooks.md Demonstrates how to use reactive options with `useKeenSlider` by passing a `computed` ref for configuration. ```javascript import { ref } from 'vue' import { useKeenSlider } from 'keen-slider/vue' const perView = ref(3) const loop = ref(true) const options = computed(() => ({ loop: loop.value, slides: { perView: perView.value }, })) const [container, slider] = useKeenSlider(options) // Update options reactively function toggleLoop() { loop.value = !loop.value // slider automatically updates via watcher } function changePerView(newValue) { perView.value = newValue // slider automatically updates } ``` -------------------------------- ### Cleanup Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Example of destroying the slider instance to clean up resources. ```typescript slider.destroy() ``` -------------------------------- ### Navigate with buttons Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Basic navigation buttons to move to the previous or next slide using the slider instance. ```typescript ``` -------------------------------- ### Slide Selection Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/renderer-web-plugin.md Examples of different ways to configure the `selector` option for slide selection. ```typescript // CSS selector string (default) { selector: '.keen-slider__slide' } // Function { selector: (container) => container.querySelectorAll('.slide') } // Array of elements { selector: [elem1, elem2, elem3] } // NodeList { selector: document.querySelectorAll('.slide') } // Disable slide selection { selector: null } ``` -------------------------------- ### Update Options Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/README.md Example of updating slider options after initialization. ```typescript slider.update({ mode: 'free-snap', drag: false, rubberband: true, }) ``` -------------------------------- ### Disable Rubberband Effect Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Example of disabling the bounce effect at boundaries. ```typescript { rubberband: false } ``` -------------------------------- ### Lock/unlock drag Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/quick-reference.md Demonstrates how to disable and re-enable dragging on the slider. ```typescript // Disable dragging slider.update({ drag: false }) // Re-enable slider.update({ drag: true }) ``` -------------------------------- ### Right-to-Left Layout Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/configuration.md Right-to-left layout. ```typescript { rtl: true } ``` -------------------------------- ### Plugin Hooks - Animation Source: https://github.com/rcbyr/keen-slider/blob/master/_autodocs/api-reference/plugins-architecture.md Examples of using plugin hooks for animation-related events. ```typescript // Animation slider.on('animationStarted', () => { // Animation began }) slider.on('animationEnded', () => { // Animation completed }) slider.on('animationStopped', () => { // Animation stopped early }) ```