# Stimulus Patterns Common controller patterns for real-world use cases. --- ## Debounced Search ```javascript // search_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['input', 'results']; static values = { url: String, delay: { type: Number, default: 300 } }; connect() { this.timeout = null; } disconnect() { clearTimeout(this.timeout); } search() { clearTimeout(this.timeout); this.timeout = setTimeout(() => this.performSearch(), this.delayValue); } async performSearch() { const query = this.inputTarget.value; if (!query) { this.resultsTarget.innerHTML = ''; return; } const url = `${this.urlValue}?q=${encodeURIComponent(query)}`; const response = await fetch(url); this.resultsTarget.innerHTML = await response.text(); } } ``` ```html
``` --- ## Loading State ```javascript // loading_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['button', 'spinner']; static classes = ['loading']; start() { this.element.classList.add(this.loadingClass); this.buttonTarget.disabled = true; this.spinnerTarget.hidden = false; } stop() { this.element.classList.remove(this.loadingClass); this.buttonTarget.disabled = false; this.spinnerTarget.hidden = true; } } ``` ```html
``` --- ## Toggle / Disclosure ```javascript // toggle_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['content']; static classes = ['open']; static values = { open: { type: Boolean, default: false } }; toggle() { this.openValue = !this.openValue; } show() { this.openValue = true; } hide() { this.openValue = false; } openValueChanged() { this.contentTarget.hidden = !this.openValue; this.element.classList.toggle(this.openClass, this.openValue); } } ``` ```html
``` --- ## Modal / Dialog ```javascript // modal_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['dialog']; open() { this.dialogTarget.showModal(); } close() { this.dialogTarget.close(); } closeOnBackdrop(event) { if (event.target === this.dialogTarget) { this.close(); } } closeOnEscape(event) { if (event.key === 'Escape') { this.close(); } } } ``` ```html

Modal Title

Modal content

``` --- ## Dropdown ```javascript // dropdown_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['menu']; static values = { open: { type: Boolean, default: false } }; toggle() { this.openValue = !this.openValue; } close() { this.openValue = false; } closeOnClickOutside(event) { if (!this.element.contains(event.target)) { this.close(); } } openValueChanged() { this.menuTarget.hidden = !this.openValue; } } ``` ```html
``` --- ## Tabs ```javascript // tabs_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['tab', 'panel']; static classes = ['active']; static values = { index: { type: Number, default: 0 } }; select(event) { this.indexValue = this.tabTargets.indexOf(event.currentTarget); } indexValueChanged() { this.tabTargets.forEach((tab, i) => { tab.classList.toggle(this.activeClass, i === this.indexValue); tab.setAttribute('aria-selected', i === this.indexValue); }); this.panelTargets.forEach((panel, i) => { panel.hidden = i !== this.indexValue; }); } } ``` ```html
Content 1
``` --- ## Form Validation ```javascript // validation_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['submit']; validate(event) { const field = event.target; const error = field.nextElementSibling; if (field.validity.valid) { error.hidden = true; field.classList.remove('is-invalid'); } else { error.textContent = field.validationMessage; error.hidden = false; field.classList.add('is-invalid'); } this.updateSubmit(); } updateSubmit() { const form = this.element; this.submitTarget.disabled = !form.checkValidity(); } submit(event) { if (!this.element.checkValidity()) { event.preventDefault(); this.element.reportValidity(); } } } ``` ```html
``` --- ## Clipboard Copy ```javascript // clipboard_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['source', 'button']; static values = { successText: { type: String, default: 'Copied!' } }; async copy() { const text = this.sourceTarget.value || this.sourceTarget.textContent; await navigator.clipboard.writeText(text); const originalText = this.buttonTarget.textContent; this.buttonTarget.textContent = this.successTextValue; setTimeout(() => { this.buttonTarget.textContent = originalText; }, 2000); } } ``` ```html
``` --- ## Auto-Submit Form ```javascript // auto_submit_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static values = { delay: { type: Number, default: 500 } }; connect() { this.timeout = null; } disconnect() { clearTimeout(this.timeout); } submit() { clearTimeout(this.timeout); this.timeout = setTimeout(() => { this.element.requestSubmit(); }, this.delayValue); } } ``` ```html
``` --- ## Character Counter ```javascript // counter_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['input', 'count']; static values = { max: Number }; static classes = ['over']; connect() { this.update(); } update() { const count = this.inputTarget.value.length; const remaining = this.maxValue - count; this.countTarget.textContent = `${count}/${this.maxValue}`; this.countTarget.classList.toggle(this.overClass, remaining < 0); } } ``` ```html
``` --- ## Infinite Scroll ```javascript // infinite_scroll_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['sentinel', 'container']; static values = { url: String, page: { type: Number, default: 1 } }; connect() { this.observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) this.loadMore(); }); }); this.observer.observe(this.sentinelTarget); } disconnect() { this.observer.disconnect(); } async loadMore() { this.pageValue++; const url = `${this.urlValue}?page=${this.pageValue}`; const response = await fetch(url); const html = await response.text(); this.sentinelTarget.insertAdjacentHTML('beforebegin', html); } } ``` ```html
``` --- ## Sortable List ```javascript // sortable_controller.js import { Controller } from '@hotwired/stimulus'; export default class extends Controller { static targets = ['item']; dragstart(event) { event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', event.target.dataset.id); event.target.classList.add('dragging'); } dragend(event) { event.target.classList.remove('dragging'); } dragover(event) { event.preventDefault(); const dragging = this.element.querySelector('.dragging'); const target = event.target.closest('[data-sortable-target="item"]'); if (target && target !== dragging) { const rect = target.getBoundingClientRect(); const after = event.clientY > rect.top + rect.height / 2; target.parentNode.insertBefore(dragging, after ? target.nextSibling : target); } } } ``` ```html ```