Basic Stimulus example
The simplest possible Stimulus controller featuring two targets and the data API
HTML
<script src="https://unpkg.com/[email protected]/dist/stimulus.umd.js"></script>
<!-- this works in Stimulus 1.1.1 -->
<div data-controller="conversion" data-conversion-rate="0.881709">
$ <input data-target="conversion.input" type="text" data-action="keyup->conversion#calculate">
= <span data-target="conversion.converted"></span>
</div>
JavaScript
// This is the most basic example of a Stimulus controller. It converts the price in $ to Euros.
// See https://dev.to/borama/a-few-sneak-peeks-into-hey-com-technology-v-stimulus-enhancements-gea.
const application = Stimulus.Application.start()
application.register("conversion", class extends Stimulus.Controller {
// see https://stimulusjs.org/handbook/installing#using-without-a-build-system for an explanation of this syntax
static get targets() {
return ["input", "converted"]
}
calculate() {
const value = this.inputTarget.value
const convertedValue = parseFloat(this.data.get("rate")) * parseFloat(value)
this.convertedTarget.textContent = "EUR " + convertedValue.toFixed(2)
}
})