Wednesday, December 31, 2025

Intro to Hotwire: HTML over the wire

In Stimulus, you utilize HTML attributes to attach parts to “controllers,” that are chunks of JavaScript performance. For instance, if we wished to supply a clipboard copy button, we might do one thing like this:

A fragile, native berry with giant, mushy leaves.

Discover the data-contoller attribute. That hyperlinks the component to the clipboard controller. Stimulus makes use of a filename conference, and on this case, the file can be: clipboard_controller.js, with contents one thing like this:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  // Connects to data-clipboard-target="supply" 
  // and data-clipboard-target="suggestions"
  static targets = [ "source", "feedback" ]

  // Runs when data-action="click->clipboard#copy" is triggered
  copy() {
    // 1. Get textual content from the "supply" goal
    const textToCopy = this.sourceTarget.textContent
    
    // 2. Use the browser's clipboard API
    navigator.clipboard.writeText(textToCopy)

    // 3. Replace the "suggestions" goal to inform the consumer
    this.feedbackTarget.textContent = "Copied!"

    // 4. (Elective) Reset the button after 2 seconds
    setTimeout(() => {
      this.feedbackTarget.textContent = "Copy Identify"
    }, 2000)
  }
}

The static goal member gives these parts to the controller to work with, primarily based on the data-clipboard-target attribute within the markup. The controller then makes use of easy JavaScript to carry out the clipboard copy and a timed message to the UI.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com