fregante / fit-textarea

Automatically expand a <textarea> to fit its content, in a few bytes
https://npmjs.com/fit-textarea
MIT License
78 stars 2 forks source link

Dispatch events when textarea is resized #20

Open cheap-glitch opened 2 years ago

cheap-glitch commented 2 years ago

Would be nice to be able to listen to shrink/expand events on the textarea element.

Use case: I have an auto-fit textarea at the bottom of a page, and I'd like to keep the vertical scroll all the way down as it's expanding. The browser kinda does this, but due to padding on the textarea the bottom is always cut off a little bit.

fregante commented 2 years ago
new ResizeObserver(console.log).observe(document.querySelector('textarea'))

also works on user resizes. Test on this page

cheap-glitch commented 2 years ago

Yeah, that's what I use right now but it feels backwards. Since I disable manual resizing anyway, it makes more sense imo to "hook" into fixTextarea internals.

fregante commented 2 years ago

Should be as simple as textarea.dispatchEvent(new CustomEvent('fit-textarea', {bubble, etc})), but what would you use it for?

cheap-glitch commented 2 years ago

Use case: I have an auto-fit textarea at the bottom of a page, and I'd like to keep the vertical scroll all the way down as it's expanding. The browser kinda does this, but due to padding on the textarea the bottom is always cut off a little bit.

This could be fixed with something like textarea.addEventListener('grow', window.scroll({ top: 9999 }))

fregante commented 2 years ago

I don’t think that's safe. What if the textarea is 200vh and the user is typing at the top? A resize would move the caret out of the viewport. Scrolling while typing is dangerous and it's not easy to find the position of the caret on scree if I remember correctly.

fregante commented 2 years ago

It'd be nice to make this part of fit-textarea, but also even just moving the caret higher while the user is typing feels unnatural. Essentially, a line break would move the caret at the beginning of the same line on screen, like a type-writer. 🤔