-
-
Save goulvench/4651de72fcbe0e5b1b6c4543341f4b35 to your computer and use it in GitHub Desktop.
Auto Growing text-area [Stimulus] [Rails]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= text_area_tag :name, content, data: { controller: 'autogrow', action: 'autogrow#resize' } %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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] | |
} | |
} | |
} |
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
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.