Skip to content

Instantly share code, notes, and snippets.

@chamakits
Created February 22, 2020 00:33
Show Gist options
  • Save chamakits/0f41063c231d65302b9baa7053db7b54 to your computer and use it in GitHub Desktop.
Save chamakits/0f41063c231d65302b9baa7053db7b54 to your computer and use it in GitHub Desktop.
StimulusJS Adding Elements Dynamically
class AutocompleteController extends Stimulus.Controller {
static get targets() {
return [ "results" ]
}
initialize() {
this.fakeFetch()
setInterval(this.fakeFetch.bind(this), 1500)
}
redirect(event) {
alert(`Redirect! "${event.currentTarget.textContent.trim()}"`)
}
fakeFetch() {
const length = Math.ceil(Math.random() * 20) + 2
this.resultsTarget.innerHTML = Array.from({ length }, () => `
<li data-action="click->autocomplete#redirect">
${Math.random().toString().slice(-10)}
</li>`
).join("")
}
}
const application = Stimulus.Application.start()
application.register("autocomplete", AutocompleteController)
<!-- from: https://jsfiddle.net/javan/x4p8n7mb/ -->
<div data-controller="autocomplete">
<ul data-target="autocomplete.results"></ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment