jackmoore / autosize

Autosize is a small, stand-alone script to automatically adjust textarea height to fit text.
http://www.jacklmoore.com/autosize/
MIT License
5.1k stars 702 forks source link

Not possible to use CSS transiton #375

Closed mkasprz closed 5 years ago

mkasprz commented 5 years ago

Hi. I'd like to add CSS height transition when I manually call the update method, but it doesn't work. I believe it's connected with this line: https://github.com/jackmoore/autosize/blob/d32047a7c06d81fedb12e0e9bfdd108e3a0a68f1/src/autosize.js#L111 . Could You explain why is it necessary if so? Would it be possible to change the code a bit to allow transitions or would it be a major change?

jackmoore commented 5 years ago

@mkasprz It would require a completely different approach. As you type, this script calculates height by removing the textarea's height and measuring the amount of overflow it has using scrollHeight. Then it restores the height to match whatever the scrollHeight was. This change in height has to happen very quickly to not be noticeable, which is incompatible with using a CSS transition.

An alternative approach that would allow transitions would be to use an offscreen textarea element, and mirror the text into it and use that as a basis for height calculations, but that opens up a lot of issues with making sure that textarea has the exact same size constraints as the visible textarea element (same dimensions, restrictions, multitude of type-face related styles, etc.). Autosize used to work that way when it was still a jQuery plugin, but I feel like it's too fraught with issues.

I think before I went down that path again, I would just use a content-editable div and try to make it work like a textarea element, instead of the other way around.

mkasprz commented 5 years ago

Thank You for the clarification.

contenteditable div has it's characteristics (downsides in my case) like possibility to paste there any HTML code or usage of <br/> to represent the new line character. Anyway, thank You for the suggestion.

I also tried writing down a work-around to listen to transitionend event of other properties, saving the current height then, calling update method, saving the new height, 'destroying' autosize, setting height manually to trigger the transition and reapplying autosize. I haven't managed to make it work perfectly (at least until this post edit), event though I think it's possible, but it's probably not a ideal solution anyway as it ends up with having to animations instead of one and too complicated maybe, but it's probably better then nothing.