Created
October 17, 2014 11:23
-
-
Save sylvaindethier/8dcabfd8f2a0bada8ac5 to your computer and use it in GitHub Desktop.
Revisions
-
sylvaindethier created this gist
Oct 17, 2014 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,47 @@ <textarea data-adaptheight rows="3" cols="40" placeholder="Your input" style="padding: 16px; line-height: 1.5;"></textarea> <script> (function() { function adjustHeight(textareaElement, minHeight) { // compute the height difference which is caused by border and outline var outerHeight = parseInt(window.getComputedStyle(el).height, 10); var diff = outerHeight - el.clientHeight; // set the height to 0 in case of it has to be shrinked el.style.height = 0; // set the correct height // el.scrollHeight is the full height of the content, not just the visible part el.style.height = Math.max(minHeight, el.scrollHeight + diff) + 'px'; } // we use the "data-adaptheight" attribute as a marker var textAreas = document.querySelectorAll('textarea[data-adaptheight]'); // iterate through all the textareas on the page for (var i = 0, l = textAreas.length; i < l; i++) { var el = textAreas[i]; // we need box-sizing: border-box, if the textarea has padding el.style.boxSizing = el.style.mozBoxSizing = 'border-box'; // we don't need any scrollbars, do we? :) el.style.overflowY = 'hidden'; // the minimum height initiated through the "rows" attribute var minHeight = el.scrollHeight; el.addEventListener('input', function() { adjustHeight(el, minHeight); }); // we have to readjust when window size changes (e.g. orientation change) window.addEventListener('resize', function() { adjustHeight(el, minHeight); }); // we adjust height to the initial content adjustHeight(el, minHeight); } }()); </script>