### Basic useIdle example Source: https://stimulus-use.dev/use-idle.html Basic example of using useIdle with a custom idle timeout of 3000 milliseconds. ```js connect() { useIdle(this, { ms: 3000 }); } ``` -------------------------------- ### Install with Yarn Source: https://stimulus-use.dev/getting_started.html Install Stimulus Use with Yarn in a project that uses a build system. ```bash yarn add stimulus-use ``` -------------------------------- ### Install with npm Source: https://stimulus-use.dev/getting_started.html Install Stimulus Use with npm in a project that uses a build system. ```bash npm i stimulus-use ``` -------------------------------- ### Install dependencies with yarn Source: https://stimulus-use.dev/playground.html Install project dependencies after cloning the repository. ```bash yarn install ``` -------------------------------- ### Install stimulus-use with yarn for Stimulus 3 Source: https://stimulus-use.dev/ Installs stimulus-use and @hotwired/stimulus via yarn for use with Stimulus 3. ```bash yarn add stimulus-use @hotwired/stimulus ``` -------------------------------- ### Install preview build with npm Source: https://stimulus-use.dev/getting_started.html Install an unreleased preview build from a commit or pull request using npm. Replace {commit} with a commit SHA (e.g. 209b96d) or a pull request number (e.g. 606). ```bash npm i https://pkg.pr.new/stimulus-use@{commit} ``` -------------------------------- ### Install preview build with Yarn Source: https://stimulus-use.dev/getting_started.html Install an unreleased preview build from a commit or pull request using Yarn. Replace {commit} with a commit SHA (e.g. 209b96d) or a pull request number (e.g. 606). ```bash yarn add https://pkg.pr.new/stimulus-use@{commit} ``` -------------------------------- ### Install stimulus-use with npm for Stimulus 3 Source: https://stimulus-use.dev/ Installs stimulus-use and @hotwired/stimulus via npm for use with Stimulus 3. ```bash npm i stimulus-use @hotwired/stimulus ``` -------------------------------- ### Install hotkeys-js dependency Source: https://stimulus-use.dev/use-hotkeys.html Install the required peer dependency using yarn. ```bash yarn add hotkeys-js ``` -------------------------------- ### Start local playground with yarn Source: https://stimulus-use.dev/playground.html Launch the local playground, available at http://localhost:8080/ by default. ```bash yarn start ``` -------------------------------- ### Install stimulus-use 0.41.0 with npm for Stimulus 2 Source: https://stimulus-use.dev/ Installs stimulus-use version 0.41.0 and stimulus version 2.0.0 via npm for use with Stimulus 2 or below. ```bash npm i stimulus-use@0.41.0 stimulus@2.0.0 ``` -------------------------------- ### Controlling observation with observe/unobserve Source: https://stimulus-use.dev/use-visibility.html Shows how to get the observe and unobserve functions from useVisibility to manually control observation. Observation starts automatically and is cleaned up on disconnect. ```javascript import { Controller } from '@hotwired/stimulus' import { useVisibility } from 'stimulus-use' export default class extends Controller { connect() { const [observe, unobserve] = useVisibility(this) this.observe = observe this.unobserve = unobserve } } ``` -------------------------------- ### useIdle with all options Source: https://stimulus-use.dev/use-idle.html Example with all options: sets idle timeout to 3000ms, initial state to idle, listens only to 'click' events, disables event dispatching, and removes the event prefix. ```js connect() { useIdle(this, { ms: 3000, initialState: true, events: ['click'], dispatchEvent: false, eventPrefix: false }); } ``` -------------------------------- ### useThrottle basic implementation Source: https://stimulus-use.dev/use-throttle.html Example showing how to throttle a function by adding it to the static throttles array and calling useThrottle in the connect method. ```js import { ApplicationController, useThrottle } from 'stimulus-use' export default class extends ApplicationController { static throttles = ['add'] connect() { useThrottle(this, { wait: 100 }) } add() { // this function is throttled. } instant() { //this function is not throttled. } } ``` -------------------------------- ### Composing useApplication Source: https://stimulus-use.dev/use-application.html Example of initializing useApplication inside a standard Stimulus controller's connect method. ```javascript import { Controller } from '@hotwired/stimulus' import { useApplication } from 'stimulus-use' export default class extends Controller { connect() { useApplication(this) } } ``` -------------------------------- ### Handling Resize Events in HTML Source: https://stimulus-use.dev/use-resize.html Example of listening to the dispatched resize event in the HTML template. ```html
...
``` -------------------------------- ### HTML Controller Setup Source: https://stimulus-use.dev/use-lazy-load.html The required HTML structure for the controller element, using a data attribute to specify the image source. ```html A lazily loaded photo ``` -------------------------------- ### useThrottle per-function wait configuration Source: https://stimulus-use.dev/use-throttle.html Example demonstrating how to specify different wait times for individual functions within the throttles array. ```js export default class extends ApplicationController { static throttles = [ 'click', { name: 'fetch', wait: 500 } ] connect() { useThrottle(this, { wait: 100 }) } click() { // this function is throttled with a wait time of 100ms. } fetch() { // this function is throttled with a wait time of 500ms. } instant() { // this function is not throttled. } } ``` -------------------------------- ### Alpine JS directive style configuration Source: https://stimulus-use.dev/use-transition.html Example of data attributes used for transition states. ```html data-transition-enter-class="transform opacity-0 scale-95" data-transition-enter-start-class="transition ease-out duration-300" data-transition-enter-end-class="transform opacity-100 scale-100" data-transition-leave-class="transform opacity-100 scale-100" data-transition-leave-start-class="transition ease-in duration-300" data-transition-leave-end-class="transform opacity-0 scale-95" ``` -------------------------------- ### Custom CSS transition implementation Source: https://stimulus-use.dev/use-transition.html A complete example using custom CSS classes with the useTransition mixin in a Stimulus controller. ```html
This element will fade out and in!
``` ```js import { Controller } from '@hotwired/stimulus'; import { useTransition } from 'stimulus-use'; export default class extends Controller { static targets = ['boxToClose'] connect() { useTransition(this, { element: this.boxToCloseTarget, enterActive: 'fade-enter-active', enterFrom: 'fade-enter-from', enterTo: 'fade-enter-to', leaveActive: 'fade-leave-active', leaveFrom: 'fade-leave-from', leaveTo: 'fade-leave-to', hiddenClass: 'd-none', // set this, because the item *starts* in an open state transitioned: true, }); } close() { this.leave(); } open() { this.enter(); } toggle() { this.toggleTransition(); } } ``` ```css .fade-enter-active, .fade-leave-active { transition: opacity 500ms; } .fade-enter-from, .fade-leave-to { opacity: 0; } .fade-enter-to, .fade-leave-from { opacity: 1; } .d-none { display: none; } ``` -------------------------------- ### useHover Composing Source: https://stimulus-use.dev/use-hover.html Example of using useHover by composing it within a standard Stimulus controller. ```javascript import { Controller } from '@hotwired/stimulus' import { useHover } from 'stimulus-use' export default class extends Controller { connect() { useHover(this, { element: this.element }); } mouseEnter() { // ... } mouseLeave() { // ... } } ``` -------------------------------- ### useResize Composition Source: https://stimulus-use.dev/use-resize.html Example of using useResize by composing it within a Stimulus controller. ```javascript import { Controller } from '@hotwired/stimulus' import { useResize } from 'stimulus-use' export default class extends Controller { static targets = ['width'] connect() { useResize(this) } resize({ width }) { this.widthTarget.textContent = width } } ``` -------------------------------- ### Basic useDispatch Usage Source: https://stimulus-use.dev/use-dispatch.html Example of applying the mixin and using the dispatch function to emit a custom event from a controller. ```javascript // item_controller.js import { Controller } from '@hotwired/stimulus' import { useDispatch } from 'stimulus-use' export default class extends Controller { connect() { useDispatch(this) } add() { // dispatch a custom event item:add this.dispatch("add") } } ``` -------------------------------- ### Controlling observation with observe/unobserve Source: https://stimulus-use.dev/use-window-focus.html useWindowFocus returns an [observe, unobserve] tuple. Store them on the controller to start and stop observing manually. Observation starts automatically and is cleaned up on disconnect. ```javascript import { Controller } from '@hotwired/stimulus' import { useWindowFocus } from 'stimulus-use' export default class extends Controller { connect() { const [observe, unobserve] = useWindowFocus(this) this.observe = observe this.unobserve = unobserve } } ``` -------------------------------- ### useResize Extending Controller Source: https://stimulus-use.dev/use-resize.html Example of using useResize by extending the ResizeController class. ```javascript import { ResizeController } from 'stimulus-use' export default class extends ResizeController { static targets = ['width'] resize({ width }) { this.widthTarget.textContent = width } } ``` -------------------------------- ### Simple Hotkey Definition Source: https://stimulus-use.dev/use-hotkeys.html Example of defining multiple hotkeys using the simple format within a Stimulus controller. ```js import { Controller } from '@hotwired/stimulus' import { useHotkeys } from 'stimulus-use/hotkeys' export default class extends Controller { connect() { useHotkeys(this, { '/': [this.singleKeyHandler], 'cmd+a': [this.metaKeyHandler], b: [this.inputHandler], e: [this.inputHandler, this.inputTarget] }) } } ``` -------------------------------- ### useMatchMedia Event Handling Source: https://stimulus-use.dev/use-match-media.html Example of listening to dispatched media query events in HTML using Stimulus data attributes. ```html
...
``` -------------------------------- ### Load StimulusUse via UMD script tag Source: https://stimulus-use.dev/getting_started.html Load StimulusUse via a
…
``` -------------------------------- ### useHover Callbacks Source: https://stimulus-use.dev/use-hover.html Example of using mouseEnter and mouseLeave callbacks to manipulate element classes. ```javascript import { Controller } from '@hotwired/stimulus' import { useHover } from 'stimulus-use' export default class extends Controller { connect() { useHover(this, { element: this.element }); } mouseEnter() { // ... this.element.classList.add('active') } mouseLeave() { // ... this.element.classList.remove('active') } } ``` -------------------------------- ### useHover Events Source: https://stimulus-use.dev/use-hover.html Example of using dispatched events to trigger Stimulus actions in HTML. ```html
...
``` -------------------------------- ### useHover Extending a controller Source: https://stimulus-use.dev/use-hover.html Example of using useHover by extending the HoverController base class. ```javascript import { HoverController } from 'stimulus-use' export default class extends HoverController { mouseEnter() { // ... } mouseLeave() { // ... } } ``` -------------------------------- ### Enable global debug with application.debug Source: https://stimulus-use.dev/debug.html Enable debug globally for both Stimulus and stimulus-use. The first snippet shows the full setup with application.debug = true. The second snippet shows a dynamic alternative using the NODE_ENV environment variable. ```js import { Application } from '@hotwired/stimulus' import { definitionsFromContext } from '@hotwired/stimulus-webpack-helpers' const application = Application.start() const context = require.context('./controllers', true, /\.js$/) application.load(definitionsFromContext(context)) // enable debug mode (Stimulus + stimulus-use) application.debug = true ``` ```js application.debug = process.env.NODE_ENV === 'development' ``` -------------------------------- ### Basic useDebounce example Source: https://stimulus-use.dev/use-debounce.html Basic usage: define a static debounces array with function names, call useDebounce(this) in connect(), and the listed functions are debounced with the default options (wait 200, trailing only). Functions not listed are not debounced. ```js import { ApplicationController, useDebounce } from 'stimulus-use' export default class extends ApplicationController { static debounces = ['add'] connect() { useDebounce(this) } add() { // this function is debounced. } instant() { //this function is not debounced. } } ``` -------------------------------- ### useMatchMedia Usage Source: https://stimulus-use.dev/use-match-media.html Example of implementing useMatchMedia in a Stimulus controller to track multiple media queries and handle their state changes. ```js import { Controller } from '@hotwired/stimulus' import { useMatchMedia } from 'stimulus-use' export default class extends Controller { connect() { useMatchMedia(this, { mediaQueries: { small: '(min-width: 320px) and (max-width: 769px)', tall: '(min-height: 1000px)', light: '(prefers-color-scheme: light)', landscape: '(orientation: landscape)', } }) } smallChanged({ name, media, matches, event }) { console.log("small media query changed") } isSmall({ name, media, matches, event }) { console.log("small media query matches") } notSmall({ name, media, matches, event }) { console.log("small media query doesn't match") } // The same for // tall => tallChanged() // isTall() // notTall() // light => lightChanged() // isLight() // notLight() // landscape => landscapeChanged() // isLandscape() // notLandscape() } ``` -------------------------------- ### Composing with useIdle Source: https://stimulus-use.dev/use-idle.html Composing example: imports useIdle and uses it in a Stimulus controller's connect method, defining away and back event handlers. ```js import { Controller } from '@hotwired/stimulus' import { useIdle } from 'stimulus-use' export default class extends Controller { connect() { useIdle(this) } away(event) { alert('Hey, wake up!') } back(event) { alert('Welcome back!') } } ``` -------------------------------- ### Clone stimulus-use repository with SSH Source: https://stimulus-use.dev/playground.html Clone the stimulus-use repository using SSH to get a local copy for the playground. ```bash git clone git@github.com:stimulus-use/stimulus-use.git ``` -------------------------------- ### Extending LazyLoadController Source: https://stimulus-use.dev/use-lazy-load.html Example of implementing lazy loading by extending the provided LazyLoadController base class. ```javascript import { LazyLoadController } from 'stimulus-use' export default class extends LazyLoadController { loading(src) { // triggered when the image starts loading } loaded(src) { // triggered when the image has finished loading } } ``` -------------------------------- ### Enable per-mixin debug with debug option Source: https://stimulus-use.dev/debug.html Enable debug locally for a specific mixin by passing the debug option. This example uses useMatchMedia, but the same option applies to other mixins that support it. ```js useMatchMedia(this, { debug: true }) ``` -------------------------------- ### observe() and unobserve() methods Source: https://stimulus-use.dev/use-window-focus.html Methods to manually start and stop observing window focus. Available when extending WindowFocusController or from the returned tuple. ```APIDOC ## observe() and unobserve() methods ### Description These methods allow manual control of the window focus observation. Observation starts automatically and is cleaned up when the controller disconnects. When extending WindowFocusController, these are available as this.observe() and this.unobserve(). ### Method Function call ### Usage Call observe() to start observing, unobserve() to stop. ### Example ```js import { Controller } from '@hotwired/stimulus' import { useWindowFocus } from 'stimulus-use' export default class extends Controller { connect() { const [observe, unobserve] = useWindowFocus(this) this.observe = observe this.unobserve = unobserve } } ``` ``` -------------------------------- ### Cart Counter Example HTML Source: https://stimulus-use.dev/use-application.html HTML markup for a cart counter component using data-controller and data-action attributes. ```html
No of items: 0
``` -------------------------------- ### Extending ApplicationController Source: https://stimulus-use.dev/use-application.html Example of extending ApplicationController to gain access to built-in helpers like isPreview, isConnected, and dispatch. ```javascript import { ApplicationController } from 'stimulus-use' export default class extends ApplicationController { connect() { this.isPreview // true/false if it is a Turbolinks preview this.isConnected // true/false if the controller is connected this.dispatch("hello") // helper to dispatch a custom event "greet:hello" to other Stimulus controllers // this.dispatch() is deprecated: For more information https://stimulus-use.dev/use-dispatch#migration-guide } } ``` -------------------------------- ### Per-function debounce options example Source: https://stimulus-use.dev/use-debounce.html Per-function options: each entry in the debounces array can be a string (uses global options) or an object with name, wait, leading, and trailing. The global wait is 100ms; fetch overrides wait to 500ms, duplicate uses leading:true (both edges), and search uses leading:true with trailing:false (leading only). Functions not listed are not debounced. ```js export default class extends ApplicationController { static debounces = [ 'click', { name: 'fetch', wait: 500 }, { name: 'duplicate', leading: true }, { name: 'search', leading: true, trailing: false } ] connect() { useDebounce(this, { wait: 100 }) } click() { // this function is debounced only on the trailing edge with a wait time of 100ms. } fetch() { // this function is debounced only on the trailing edge with a wait time of 500ms. } duplicate() { // this function is debounced on both the leading and trailing edges with a wait time of 100ms. } search() { // this function is debounced on the leading edge only (runs immediately, no trailing call) with a wait time of 100ms. } instant() { //this function is not debounced. } } ``` -------------------------------- ### Using away and back events Source: https://stimulus-use.dev/use-idle.html Events example: HTML markup with data-action for the 'user:away' event and the corresponding controller that uses useIdle and defines a logout handler. ```html
...
``` ```js // user_controller.js export default class extends Controller { connect() { useIdle(this) } logout(event) { event.preventDefault() // do some actions to logout the user } } ``` -------------------------------- ### Example: pause video on window unfocus Source: https://stimulus-use.dev/use-window-focus.html A typical use case: pause a video when the user navigates tabs. The focus method plays the video, unfocus pauses it. ```javascript // video_controller.js export default class extends Controller { connect() { useWindowFocus(this) this.player = new VideoPlayer() } focus() { this.player.play() } unfocus() { this.player.pause() } } ``` -------------------------------- ### Extending TargetMutationController with options Source: https://stimulus-use.dev/use-target-mutation.html Example of extending TargetMutationController with options. It sets static targets to ["location", "view", "content"] and static options to { targets: ["location"] } to track only the location target. It implements locationTargetAdded, locationTargetRemoved, and locationTargetChanged methods. ```js import { TargetMutationController } from 'stimulus-use' export default class extends TargetMutationController { static targets = ["location", "view", "content"] static options = { targets: ["location"] } locationTargetAdded(element) { // triggered when a locationTarget is added } locationTargetRemoved(element) { // triggered when a locationTarget is removed } locationTargetChanged(element) { // triggered when a locationTarget is changed } } ``` -------------------------------- ### Using useTargetMutation in a Stimulus controller Source: https://stimulus-use.dev/use-target-mutation.html Example of using useTargetMutation in a Stimulus controller. It defines static targets and calls useTargetMutation(this) in connect(). The controller then implements locationTargetAdded, locationTargetRemoved, locationTargetChanged, contentTargetAdded, contentTargetRemoved, contentTargetChanged, viewTargetAdded, viewTargetRemoved, and viewTargetChanged methods, each logging a message when the corresponding target is added, removed, or changed. ```js export default class extends Controller { static targets = ["location", "content", "view"] connect() { useTargetMutation(this) } locationTargetAdded(element) { console.log('A location was added!') } locationTargetRemoved(element) { console.log('A location was removed!') } locationTargetChanged(element) { console.log('A location was changed!') } contentTargetAdded(element) { console.log('A content target was added!') } contentTargetRemoved(element) { console.log('A content target was removed!') } contentTargetChanged(element) { console.log('A content target was changed!') } viewTargetAdded(element) { console.log('A view target was added!') } viewTargetRemoved(element) { console.log('A view target was removed!') } viewTargetChanged(element) { console.log('A view target was changed!') } } ``` -------------------------------- ### Controlling observation with useTargetMutation Source: https://stimulus-use.dev/use-target-mutation.html Example of manually controlling observation. useTargetMutation returns an [observe, unobserve] tuple. Observation starts automatically when the mixin is called and is cleaned up when the controller disconnects. When extending TargetMutationController, the same functions are available as this.observe() and this.unobserve(). ```js connect() { const [observe, unobserve] = useTargetMutation(this) // later: unobserve() to pause, observe() to resume } ``` -------------------------------- ### Controlling observation with useIdle Source: https://stimulus-use.dev/use-idle.html Controlling observation: useIdle returns an [observe, unobserve] tuple to manually start and stop observing. Observation starts automatically and is cleaned up on disconnect. ```js import { Controller } from '@hotwired/stimulus' import { useIdle } from 'stimulus-use' export default class extends Controller { connect() { const [observe, unobserve] = useIdle(this) this.observe = observe this.unobserve = unobserve } } ``` -------------------------------- ### useDebounce(controller, options = {}) Source: https://stimulus-use.dev/use-debounce.html Initializes debouncing for the given Stimulus controller. The controller must have a static debounces array listing method names to debounce. Options include wait, leading, and trailing. ```APIDOC ## useDebounce(controller, options = {}) ### Description Initializes debouncing for the given Stimulus controller. The controller must have a static debounces array listing method names to debounce. Options include wait, leading, and trailing. ### Parameters - **controller** (Stimulus Controller) - Required - A Stimulus Controller (usually 'this') - **options** (Object) - Optional - Configuration options - **wait** (Number) - Optional - The number of milliseconds to wait (default: 200) - **leading** (Boolean) - Optional - Whether your function is called on the leading edge of the timeout (immediately) (default: false) - **trailing** (Boolean) - Optional - Whether your function is called on the trailing edge of the timeout (after wait) (default: true) ### Example ```js import { ApplicationController, useDebounce } from 'stimulus-use' export default class extends ApplicationController { static debounces = ['add'] connect() { useDebounce(this) } add() { // this function is debounced. } instant() { //this function is not debounced. } } ``` ``` -------------------------------- ### useApplication(controller, options = {}) Source: https://stimulus-use.dev/use-application.html Initializes the application controller with the given Stimulus controller and optional settings. It can be called in the connect method of a controller to enable the additional functions and getters. ```APIDOC ## useApplication(controller, options = {}) ### Description Initializes the application controller with the given Stimulus controller and optional settings. It can be called in the connect method of a controller to enable the additional functions and getters. ### Parameters - **controller** (Stimulus Controller) - Required - A Stimulus Controller, usually 'this'. - **options** (object) - Optional - Configuration options. - **overwriteDispatch** (boolean) - Optional - Whether to call the deprecated useDispatch() on the controller or not. Default: true. When true, the whole options object is passed through to useDispatch, so it also accepts all of its options: element, eventPrefix, bubbles, cancelable, and debug. ### Usage #### Composing ```js import { Controller } from '@hotwired/stimulus' import { useApplication } from 'stimulus-use' export default class extends Controller { connect() { useApplication(this) } } ``` #### Extending a controller ```js import { ApplicationController } from 'stimulus-use' export default class extends ApplicationController { connect() { this.isPreview // true/false if it is a Turbolinks preview this.isConnected // true/false if the controller is connected this.dispatch("hello") // helper to dispatch a custom event "greet:hello" to other Stimulus controllers } } ``` ### Functions - **dispatch(name, eventArgs)** - Deprecated - Helper function to dispatch events to other Stimulus controllers. - **metaValue(name)** - Returns the value of a meta attribute. ### Getters - **isPreview** - Returns true/false whether the current page is a Turbo/Turbolinks preview. - **isConnected** - Returns true/false for whether the Stimulus controller is connected or not. - **csrfToken** - Returns the CSRF token if any. ### Example: Building a cart counter with the dispatch helper #### HTML markup ```html
No of items: 0
``` #### Item controller dispatching the event ```js import { ApplicationController } from 'stimulus-use' export default class extends ApplicationController { add() { this.dispatch('add', { quantity: 1 }) } } ``` #### Cart controller receiving the event ```js import { ApplicationController } from 'stimulus-use' export default class extends ApplicationController { static targets = ['counterView'] refreshTotal(e) { this.counter += e.detail.quantity console.log(e.detail.controller) // the emitting item_controller } renderCounter() { this.counterViewTarget.textContent = this.counter } set counter(value) { this.data.set('counter', value) this.renderCounter() } get counter() { return parseInt(this.data.get('counter')) } } ``` ``` -------------------------------- ### Build library locally with yarn Source: https://stimulus-use.dev/playground.html Build the library locally before launching the playground. ```bash yarn build ``` -------------------------------- ### useMatchMedia(controller, options) Source: https://stimulus-use.dev/use-match-media.html Initializes the useMatchMedia mixin on a Stimulus controller. It sets up media query tracking and adds the is[Name], not[Name], and [name]Changed behaviors. ```APIDOC ## useMatchMedia(controller, options) ### Description Initializes the useMatchMedia mixin on a Stimulus controller. It tracks the given media queries and adds three behaviors per query: is[Name] when the query matches, not[Name] when it doesn't match, and [name]Changed when the query changes. ### Method useMatchMedia ### Parameters #### controller - **controller** (Stimulus Controller) - Required - The Stimulus controller instance, usually 'this'. #### options - **mediaQueries** (Object) - Optional - An object of media queries where the key is the name of the query and the value is a media query string. The whole query must be wrapped with parenthesis. Default: {}. - **eventPrefix** (Boolean or String) - Optional - Whether to prefix the emitted event. true prefixes with the controller identifier (e.g., users:is:small), a string prefixes with the given string (e.g., my-prefix:is:small), false removes the prefix (e.g., is:small). Default: true. - **debug** (Boolean) - Optional - Whether to log debug information. Default: false. - **dispatchEvent** (Boolean) - Optional - Whether to dispatch events. Default: true. ### Usage Example ```js import { Controller } from '@hotwired/stimulus' import { useMatchMedia } from 'stimulus-use' export default class extends Controller { connect() { useMatchMedia(this, { mediaQueries: { small: '(min-width: 320px) and (max-width: 769px)', tall: '(min-height: 1000px)', light: '(prefers-color-scheme: light)', landscape: '(orientation: landscape)', } }) } smallChanged({ name, media, matches, event }) { console.log("small media query changed") } isSmall({ name, media, matches, event }) { console.log("small media query matches") } notSmall({ name, media, matches, event }) { console.log("small media query doesn't match") } } ``` ### Events When dispatchEvent is enabled (default), the module dispatches three events for each media query, where [name] is the key of the media query (prefixed by the controller identifier by default, e.g., users:small:changed): - [name]:changed - dispatched when the media query changes. - is:[name] - dispatched when the media query matches. - not:[name] - dispatched when the media query doesn't match. Each event carries event.detail = { name, media, matches, event }. ### HTML Example ```html
...
``` ``` -------------------------------- ### Disabling event prefix Source: https://stimulus-use.dev/use-window-focus.html Example controller that disables the event prefix by passing { eventPrefix: false } to useWindowFocus. ```javascript // application_controller.js export default class extends Controller { connect() { useWindowFocus(this, { eventPrefix: false }) } } ``` -------------------------------- ### useHover Controlling observation Source: https://stimulus-use.dev/use-hover.html Example of manually controlling hover observation using the returned observe and unobserve functions. ```javascript import { Controller } from '@hotwired/stimulus' import { useHover } from 'stimulus-use' export default class extends Controller { connect() { const [observe, unobserve] = useHover(this, { element: this.element }) this.observe = observe this.unobserve = unobserve } } ``` -------------------------------- ### Composing useLazyLoad Source: https://stimulus-use.dev/use-lazy-load.html Example of integrating lazy loading by calling the useLazyLoad function within a standard Stimulus controller. ```javascript import { Controller } from '@hotwired/stimulus' import { useLazyLoad } from 'stimulus-use' export default class extends Controller { connect() { useLazyLoad(this, { rootMargin: '10%' }) } loading(src) { // triggered when the image starts loading } loaded(src) { // triggered when the image has finished loading } } ``` -------------------------------- ### useApplication Reference Source: https://stimulus-use.dev/use-application.html The function signature for initializing useApplication within a Stimulus controller. ```javascript useApplication(controller, options = {}) ``` -------------------------------- ### Window Event Listener Source: https://stimulus-use.dev/use-dispatch.html Demonstrates how to listen for events using @window when the receiver and emitter are at the same level or nested. ```html
``` -------------------------------- ### Import ApplicationController from stimulus-use Source: https://stimulus-use.dev/getting_started.html Import Stimulus Use in your Stimulus controllers after pinning it with importmap. ```javascript import { ApplicationController } from 'stimulus-use' ``` -------------------------------- ### useWindowFocus(controller, options) Source: https://stimulus-use.dev/use-window-focus.html Initializes the useWindowFocus behavior on a Stimulus controller. It adds focus and unfocus callbacks, a hasFocus state property, and focus/unfocus events. Returns an observe/unobserve tuple for manual control. ```APIDOC ## useWindowFocus(controller, options) ### Description Initializes the useWindowFocus behavior on a Stimulus controller. It tracks window focus and adds focus and unfocus callbacks, a hasFocus state property, and focus/unfocus events. Returns an observe/unobserve tuple for manual control. ### Method Function call ### Signature useWindowFocus(controller, options) ### Parameters - **controller** (Stimulus Controller) - Required - A Stimulus Controller (usually 'this'). - **options** (Object) - Optional - Configuration options. #### Options - **dispatchEvent** (boolean) - Optional - Whether to dispatch the focus/unfocus events or not (prefixed by the controller identifier by default, e.g. application:focus). Default: true. - **eventPrefix** (boolean|string) - Optional - Whether to prefix or not the emitted event. true prefixes with the controller identifier, someString prefixes with the given string, false removes prefix. Default: true. - **debug** (boolean) - Optional - Whether to log debug information. Default: false. - **interval** (number) - Optional - The interval in ms to check if the window is focused or not. Default: 200. ### Return Value Returns an [observe, unobserve] tuple to start and stop observing manually. ### Example ```js // video_controller.js export default class extends Controller { connect() { useWindowFocus(this) this.player = new VideoPlayer() } focus() { this.player.play() } unfocus() { this.player.pause() } } ``` ``` -------------------------------- ### Advanced Hotkey Definition Source: https://stimulus-use.dev/use-hotkeys.html Example of defining hotkeys with advanced options like scope, keyup/keydown events, and split keys. ```js import { Controller } from '@hotwired/stimulus' import { useHotkeys } from 'stimulus-use/hotkeys' export default class extends Controller { connect() { useHotkeys(this, { hotkeys: { '/': { handler: this.singleKeyHandler }, 'cmd+a': { handler: this.metaKeyHandler }, f: { handler: this.scopeHandler, options: { scope: 'files' } }, b: { handler: this.inputHandler }, c: { handler: this.keyUpHandler, options: { keydown: false, keyup: true } }, 'ctrl-d': { handler: this.splitKeyHandler, options: { splitKey: '-' } } }, filter: this.filter }) } singleKeyHandler(e) { // ... } } ``` -------------------------------- ### Multiple dropdown instances with useClickOutside Source: https://stimulus-use.dev/use-click-outside.html This pair shows a dropdown controller and its HTML markup. Because clickOutside is per-instance, clicking Help while Account is open closes Account (the click is outside it) and opens Help, making the widgets mutually exclusive. useClickOutside listens in the capture phase, so each instance's clickOutside runs before the toggle action. ```javascript // dropdown_controller.js import { Controller } from '@hotwired/stimulus' import { useClickOutside } from 'stimulus-use' export default class extends Controller { static targets = ['menu'] connect() { useClickOutside(this) } toggle() { this.menuTarget.classList.toggle('hidden') } clickOutside() { this.menuTarget.classList.add('hidden') } } ``` ```html
``` -------------------------------- ### useMatchMedia Reference Source: https://stimulus-use.dev/use-match-media.html The function signature for initializing useMatchMedia within a Stimulus controller. ```javascript useMatchMedia(controller, options) ``` -------------------------------- ### Simple options format Source: https://stimulus-use.dev/use-hotkeys.html The simple format for defining hotkeys as a mapping of keys to handlers and optional elements. ```typescript { [hotkey: string]: [handler: KeyHandler, element: HTMLElement] } ``` -------------------------------- ### Apply Vue JS directive style transitions Source: https://stimulus-use.dev/use-transition.html Example of using data attributes to define transition states, compatible with Tailwind CSS classes. ```html data-transition-enter-active="transition ease-out duration-300" data-transition-enter-from="transform opacity-0 scale-95" data-transition-enter-to="transform opacity-100 scale-100" data-transition-leave-active="transition ease-in duration-300" data-transition-leave-from="transform opacity-100 scale-100" data-transition-leave-to="transform opacity-0 scale-95" ``` -------------------------------- ### IntersectionController appear method example Source: https://stimulus-use.dev/ Use this controller to respond when an element appears within the viewport. The appear method is triggered automatically by the IntersectionController from stimulus-use. ```javascript export default class extends IntersectionController { appear(entry) { // triggered when the element appears within the viewport } } ``` -------------------------------- ### Pin hotkeys-js with importmap Source: https://stimulus-use.dev/use-hotkeys.html Configure importmap for the stimulus-use hotkeys module and the hotkeys-js library. ```bash bin/importmap pin stimulus-use/hotkeys bin/importmap pin hotkeys-js ```