Stimulus.js: clipboard controller
This course reads one small Stimulus controller that copies text to the clipboard without a page reload. It covers how data-controller and target attributes connect the class to HTML, and how data-action works in full form and with element default events. It explains the async navigator.clipboard.writeText() call, its secure context requirement, and the deprecated document.execCommand('copy') fallback. It then opens showToast(), which builds a toast from an HTML string and reuses another controller's dismiss behavior. The last lesson reads the three pages that use the controller.
What you'll learn
- ✓How data-controller and data-*-target attributes connect a Stimulus controller to HTML
- ✓The full data-action descriptor and Stimulus default events per element
- ✓How navigator.clipboard.writeText() returns a Promise and needs a secure context
- ✓Why the deprecated execCommand('copy') fallback depends on a prior .select() call
- ✓Building a toast from an HTML string and reusing another controller through shared attributes
- ✓Using the same controller with a visible or a hidden source element
Copying without a page reload
A lesson's image manager shows a generated image URL next to a small copy icon. Clicking the icon puts the URL on the clipboard, a toast confirms it, and nothing else on the page moves. No form submits, no request goes to the server, and no Turbo navigation happens. The whole feature lives in one…
Read the full lesson free →Curriculum
7 lessonsCopying without a page reload
Reads the clipboard controller file and explains why writing to the clipboard needs JavaScript in the browser.
Targets: wiring the source element
Shows how data-controller and data-ui--clipboard-target attach the controller and produce this.sourceTarget for the input.
Actions and the default-event shorthand
Explains the full data-action descriptor and why the button can use the default-event shorthand while the input cannot.
The Clipboard API: navigator.clipboard.writeText
Covers the Promise returned by writeText(), the secure context requirement, preventDefault() and the select() call.
The execCommand fallback
Opens the catch block and the deprecated execCommand('copy') fallback, with its own try/catch and return value check.
showToast and cross-controller reuse
Reads showToast(), which builds a toast inside #flash-region and reuses the ui--flash controller's dismiss behavior.
The other call sites, and putting it together
Reads the profile and certificate pages that use a hidden source input, then reviews the whole course.