Created
April 9, 2020 21:55
-
-
Save leastbad/b82329ce588f5dd26542f8ebc6ff427e to your computer and use it in GitHub Desktop.
autosize controller
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
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() | |
} | |
} |
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 "#{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