Skip to content

Instantly share code, notes, and snippets.

@leastbad
Created April 9, 2020 21:55
Show Gist options
  • Save leastbad/b82329ce588f5dd26542f8ebc6ff427e to your computer and use it in GitHub Desktop.
Save leastbad/b82329ce588f5dd26542f8ebc6ff427e to your computer and use it in GitHub Desktop.
autosize controller
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "input" ]
connect() {
this.minHeight = this.inputTarget.dataset.minHeight
if (this.minHeight == undefined) this.findLineHeight()
this.update()
}
update() {
if (this.visible()) {
this.resize()
} else {
const that = this
const observer = new IntersectionObserver((entries) => {
if(entries[0].isIntersecting === true)
that.resize()
}, { threshold: [0] });
return observer.observe(this.inputTarget)
}
}
visible() {
const observer = new IntersectionObserver((entries) => {
return entries[0].isIntersecting
}, { threshold: [0] });
return observer.observe(this.inputTarget)
}
resize() {
this.inputTarget.style.height = "auto"
let height = this.minHeight
height = this.inputTarget.scrollHeight > height ? this.inputTarget.scrollHeight : height
this.inputTarget.style.height = `${height}px`
}
findLineHeight() {
let temp = document.createElement("input")
temp.setAttribute("type", "text")
temp.classList.add(this.element.dataset.singleLineClass)
temp.innerHTML = "blah"
temp = document.body.appendChild(temp)
this.minHeight = temp.clientHeight
temp.remove()
}
}
<%= text_area_tag "#{object.class.name.downcase}[title_draft]",
object.send(:title_draft),
rows: 2,
class: "post_title_draft",
maxlength: 500,
data: { controller: "auto-resize-height",
target: "auto-resize-height.input",
action: "input->auto-resize-height#update",
single_line_class: "post_title_draft" } %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment