Thursday, May 24, 2012

JavaScript Auto Expand Textarea

Versi Dasar

function expandTextarea(id) {
    document.getElementById(id).addEventListener('keyup', function() {
        this.style.overflow = 'hidden';
        this.style.height = 0;
        this.style.height = this.scrollHeight + 'px';
    }, false);
}

Penggunaan

expandTextarea('id-textarea');

Lihat Demo

Dalam Bentuk Plugin jQuery (Dengan Sedikit Perubahan)

/**
 * TextAreaExpander plugin for jQuery
 * v1.0
 * Expands or contracts a textarea height depending on the
 * quatity of content entered by the user in the box.
 *
 * By Craig Buckler, Optimalworks.net
 * With some modification by Taufik
 * As featured on SitePoint.com:
 * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
 *
 * Please use as you wish at your own risk.
 */

/**
 * Usage:
 *
 * From JavaScript, use:
 *     $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
 *     where:
 *       <node> is the DOM node selector, e.g. "textarea"
 *       <minHeight> is the minimum textarea height in pixels (optional)
 *       <maxHeight> is the maximum textarea height in pixels (optional)
 *
 * Alternatively, in you HTML:
 *     Assign a class of "expand" to any <textarea> tag.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
 *
 *     Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
 *     The textarea will use an appropriate height between 50 and 200 pixels.
 */

(function($) {
    // jQuery plugin definition
    $.fn.TextAreaExpander = function(minHeight, maxHeight) {
        var hCheck = !($.browser.msie || $.browser.opera);
        // resize a textarea
        function ResizeTextarea(e) {
            // event or initialize element?
            e = e.target || e;
            // find content length and box width
            var vlen = e.value.length,
                ewidth = e.offsetWidth;
            if (vlen != e.valLength || ewidth != e.boxWidth) {
                if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
                var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));
                e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
                e.style.height = h + "px";
                e.valLength = vlen;
                e.boxWidth = ewidth;
            }
            return true;
        };

        // initialize
        this.each(function() {
            // is a textarea?
            if (this.nodeName.toLowerCase() != "textarea") return;
            // set height restrictions
            var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
            this.expandMin = minHeight || (p ? parseInt('0' + p[1], 10) : 0);
            this.expandMax = maxHeight || (p ? parseInt('0' + p[2], 10) : 99999);
            // initial resize
            ResizeTextarea(this);
            // zero vertical padding and add events
            if (!this.Initialized) {
                this.Initialized = true;
                $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
            }
        });
        return this;
    };
})(jQuery);

Penggunaan

Dasar

Seleksi sebuah <textarea> kemudian terapkan fungsi .TextAreaExpander(min-height, max-height):

$('textarea').TextAreaExpander(200, 700);

Tinggi Minimal & Maksimal dalam Kelas

Berikan kelas expandMinHeight-MaxHeight pada <textarea>:

<textarea class="expand50-200"></textarea>
$('textarea[class*=expand]').TextAreaExpander();

Lihat Demo


Referensi: Snipplr - Dynamically Expand a Textarea Based On the Amount of Text, TextAreaExpander Demonstration

Labels: ,

9 Comments:

At Thursday, May 24, 2012 at 7:29:00 PM GMT+7, Blogger Sinto said...

Wew seperti search engine stackoverflow ye :D

 
At Thursday, May 24, 2012 at 7:51:00 PM GMT+7, Blogger Unknown said...

Ijin simpan code-nya dulu yach bang...
Sekalian mau bilang mengamankan posisi pertama...

 
At Friday, May 25, 2012 at 9:43:00 AM GMT+7, Blogger Unknown said...

@Suwardi Unggit ngga bagi2 posisi pertama buat saya :P

 
At Friday, May 25, 2012 at 4:22:00 PM GMT+7, Blogger Unknown said...

Siiip mas..
saya sudah memakai ini :v

 
At Monday, May 28, 2012 at 3:38:00 PM GMT+7, Blogger Rohis Facebook said...

org super awwam bertanya :( , mislx sy ingin memasukkan kalimat 'Saya cakep' gmn carax tuh..??, kode2 apa sj yg mengapit kalimat 'Saya Cakep', mf merepotkan.. \o/

 
At Monday, May 28, 2012 at 7:02:00 PM GMT+7, Blogger Taufik Nurrohman said...

@Rohis Facebook

<textarea placeholder="Saya cakep"></textarea>
<textarea>Saya cakep</textarea>

 
At Tuesday, May 29, 2012 at 6:39:00 PM GMT+7, Blogger Rohis Facebook said...

@Taufik Nurrohman oke mas.., makasij y.... :-bd

 
At Tuesday, June 12, 2012 at 11:18:00 AM GMT+7, Blogger Harris said...

narses bet dagh -_-"

 
At Tuesday, September 4, 2012 at 1:15:00 PM GMT+7, Blogger mr_Q said...

Terima kasih sobat. sangat membantu kerjaan saya :). wah nice blog banget. mau tanya-tanya dong gimana sih buat template blogger sendiri. like this blog ?

 

Post a Comment

<< Home