Created
February 4, 2019 13:09
-
-
Save arodu/a69877df78d86dfc8812b018d855c0fb to your computer and use it in GitHub Desktop.
textarea autoresize vanillajs
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
| <!DOCTYPE html> | |
| <html lang="en" dir="ltr"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <title>textarea autoresize</title> | |
| <style media="screen"> | |
| textarea { | |
| min-height: 5em; | |
| width: 100%; | |
| resize:none; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <textarea></textarea> | |
| <script type="text/javascript"> | |
| var autoExpand = function (field) { | |
| // Reset field height | |
| field.style.height = 'inherit'; | |
| // Get the computed styles for the element | |
| var computed = window.getComputedStyle(field); | |
| // Calculate the height | |
| var height = parseInt(computed.getPropertyValue('border-top-width'), 10) | |
| + parseInt(computed.getPropertyValue('padding-top'), 10) | |
| + field.scrollHeight | |
| + parseInt(computed.getPropertyValue('padding-bottom'), 10) | |
| + parseInt(computed.getPropertyValue('border-bottom-width'), 10); | |
| field.style.height = height + 'px'; | |
| }; | |
| document.addEventListener('input', function (event) { | |
| if (event.target.tagName.toLowerCase() !== 'textarea') return; | |
| autoExpand(event.target); | |
| }, false); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment