Skip to content

Instantly share code, notes, and snippets.

@goulvench
Forked from yunusemredilber/_form.html.erb
Last active April 30, 2023 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goulvench/4651de72fcbe0e5b1b6c4543341f4b35 to your computer and use it in GitHub Desktop.
Save goulvench/4651de72fcbe0e5b1b6c4543341f4b35 to your computer and use it in GitHub Desktop.
Auto Growing text-area [Stimulus] [Rails]
<%= text_area_tag :name, content, data: { controller: 'autogrow', action: 'autogrow#resize' } %>
// Autogrow textarea as text changes
//
// Usage <%= text_area_tag :name, content, data: { controller: 'autogrow', action: 'autogrow#resize' } %>
import { Controller } from "stimulus"
export default class extends Controller {
connect() {
this.setStyles({
resize: 'none',
overflow: 'hidden'
})
this.resize()
}
resize(){
this.setStyles({height: '5px'}) // Force textarea to shrink back to its minimum height
this.setStyles({height: this.scrollHeight})
}
get scrollHeight() {
return this.element.scrollHeight + 'px'
}
setStyles(styles) {
for (var property in styles) {
this.element.style[property] = styles[property]
}
}
}
@goulvench
Copy link
Author

Forked to simplify HTML by setting all data attributes on the textarea.
JS code also made DRYer by adding a scrollHeight getter and a setStyle method.

@goulvench
Copy link
Author

Updated to use this.element instead of specifying a target, and shortening data-action because input is the default event on textareas and inputs (documentation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment