Thursday, June 2, 2011

Textarea Autoexpand Javascript code.

As part of a project for a consulting job I'm on, the need we had was to give a forever expanding text area on the html form.  This is the javascript I wrote to do just that.  I'm sharing it because mainly, I think it's cool!

I should have documented how this works. What you'll do in the Html is to define a text area (could be an asp TextBox with its mode set to Multiple, or a generic TextArea tag... either way, they render out the same.) and you'll add an attribute called expandable and set its value equal to True.  From there, reference jQuery in your header, and this code should work for you as-is.

Have at it, and comment if you see where I could improve in some way.

          function formatPage() {
            $(document).find('*[expandable]').keyup(function () {
                var height = 0;
                var existingHeight = this.style.height;
                var lines = this.value.split('\r');
                this.style.height = '';
                for (x = 0; x < lines.length; x++) {
                    var lengthOverflow = lines[x].length % this.cols;

                    height = height + (14 * (((lines[x].length - lengthOverflow) / this.cols)));
                    if (lengthOverflow > 0) {
                        height = height + 14;
                    }
                }

                if (height == 0) {
                    height = 14;
                }

                if (existingHeight != height) {
                    this.style.height = height + 'px';
                }
            });

            $(document).find('*[expandable]').keyup();
        }

        $(document).ready(function () {
            formatPage();
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        });


        function endRequestHandler(sender, args) {
            formatPage();
        }

No comments: