Home Update Intro to Hotwire: HTML over the wire

Intro to Hotwire: HTML over the wire

10
speed fast race car shutterstock 1168856884

In Stimulus, you employ 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 may do one thing like this:

<div data-controller="clipboard">
 
  <h1 data-clipboard-target="source">
    Thimbleberry (Rubus parviflorus)
  </h1>
  <p>A fragile, native berry with giant, comfortable leaves.</p>

  <button data-action="click->clipboard#copy">
    
    <span data-clipboard-target="feedback">Copy Name</span>
  </button>
</div>

Notice the data-contoller attribute. That hyperlinks the ingredient to the clipboard controller. Stimulus makes use of a filename conference, and on this case, the file could 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="source" 
  // and data-clipboard-target="feedback"
  static targets = [ "source", "feedback" ]

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

    // 3. Update the "feedback" goal to inform the consumer
    this.feedbackTarget.textContent = "Copied!"

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

The static goal member offers 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.



Source hyperlink

LEAVE A REPLY

Please enter your comment!
Please enter your name here