Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Created June 29, 2025 23:34
Show Gist options
  • Save bensheldon/c68fbc7e7962bde5860ab4b5700585bb to your computer and use it in GitHub Desktop.
Save bensheldon/c68fbc7e7962bde5860ab4b5700585bb to your computer and use it in GitHub Desktop.
import { Controller } from "@hotwired/stimulus"
import { debounce } from "lib/utils"
export default class extends Controller {
static values = {
resizeDebounceDelay: {
type: Number,
default: 100,
}
}
initialize() {
this.autogrow = this.autogrow.bind(this)
this.onResize = this.resizeDebounceDelayValue > 0 ? debounce(this.autogrow, this.resizeDebounceDelayValue) : this.autogrow
}
connect() {
this.element.style.overflow = "hidden" // hide the scrollbar
this.autogrow()
this.element.addEventListener("input", this.autogrow)
window.addEventListener("resize", this.onResize)
}
disconnect() {
this.element.removeEventListener("input", this.autogrow)
window.removeEventListener("resize", this.onResize)
}
autogrow() {
const height = parseFloat(this.element.style.height.replace(/px$/, "")) // Remove "px" suffix
if (height > this.element.scrollHeight) {
const lineHeight = parseFloat(getComputedStyle(this.element).lineHeight)
this.element.style.height = `${this.element.scrollHeight - lineHeight}px`
}
this.element.style.height = `${this.element.scrollHeight}px`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment