Thursday 4 September 2014

Expand and Collapse Textarea Automatically When Typing

I was searching one day for ways to expand the textarea automatically, but couldn't find any solutions that were quite what I wanted. Some required hacks to CSS, others to HTML. As a result, I decided to write my own JQuery based script that would do the job.

Here are some of its features:
  • Textarea expands and collapses automatically when typing
  • Textarea expands automatically when pasting text into it
  • If updated dynamically, it will not expand on change but it will expand the moment it gets focus
  • Works with textareas that are added using AJAX
  • Very lightweight, as it does NOT use JQuery
  • Fully cross-browser compatible

To install the code, simply include it anywhere on your page (header or body).

(function() {
    function resizeTextArea(event) {
        var e = event || window.event;
        var o = e.target || e.srcElement;
        if (!(o instanceof HTMLTextAreaElement)) return;
        if (o.getAttribute('data-rows') === null)
            o.setAttribute('data-rows', o.rows);
        addEventListener(o, 'blur', restoreTextArea);
        while (o.rows > 1 && o.rows >= o.getAttribute('data-rows') && o.scrollHeight < o.offsetHeight)
            o.rows--;
        for (h = 0; o.scrollHeight > o.offsetHeight && h !== o.offsetHeight; o.rows++)
            h = o.offsetHeight;

    }
    function restoreTextArea(event) {
        var e = event || window.event;
        var o = e.target || e.srcElement;
        if (!(o instanceof HTMLTextAreaElement)) return;
        o.rows = o.getAttribute('data-rows');
    }
    function addEventListener(o, e, f) {
        if (o.addEventListener)
            o.addEventListener(e, f, false);
        else if (o.attachEvent)
            o.attachEvent('on' + e, f);
    }
    addEventListener(document, 'click', resizeTextArea);
    addEventListener(document, 'keydown', resizeTextArea);
    addEventListener(document, 'keyup', resizeTextArea);
}());

No comments:

Post a Comment