3 * @descripton Elastic is Jquery plugin that grow and shrink your textareas automaticliy
5 * @requires Jquery 1.2.6+
8 * @author-email jan.jarfalk@unwrongest.com
9 * @author-website http://www.unwrongest.com
11 * @licens MIT License - http://www.opensource.org/licenses/mit-license.php
18 // We will create a div clone of the textarea
19 // by copying these attributes from the textarea to the div.
31 return this.each( function() {
33 // Elastic only works on textareas
34 if ( this.type != 'textarea' ) {
38 var $textarea = jQuery(this),
39 $twin = jQuery('<div />').css({'position': 'absolute','display':'none','word-wrap':'break-word'}),
40 lineHeight = parseInt($textarea.css('line-height'),10) || parseInt($textarea.css('font-size'),'10'),
41 minheight = parseInt($textarea.css('height'),10) || lineHeight*3,
42 maxheight = parseInt($textarea.css('max-height'),10) || Number.MAX_VALUE,
46 // Opera returns max-height of -1 if not set
47 if (maxheight < 0) { maxheight = Number.MAX_VALUE; }
49 // Append the twin to the DOM
50 // We are going to meassure the height of this, not the textarea.
51 $twin.appendTo($textarea.parent());
53 // Copy the essential styles (mimics) from the textarea to the twin
54 var i = mimics.length;
56 $twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));
60 // Sets a given height and overflow state on the textarea
61 function setHeightAndOverflow(height, overflow){
62 curratedHeight = Math.floor(parseInt(height,10));
63 if($textarea.height() != curratedHeight){
64 $textarea.css({'height': curratedHeight + 'px','overflow':overflow});
70 // This function will update the height of the textarea if necessary
73 // Get curated content from the textarea.
74 var textareaContent = $textarea.val().replace(/&/g,'&').replace(/ /g, ' ').replace(/<|>/g, '>').replace(/\n/g, '<br />');
76 var twinContent = $twin.html();
78 if(textareaContent+' ' != twinContent){
80 // Add an extra white space so new rows are added when you are at the end of a row.
81 $twin.html(textareaContent+' ');
83 // Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
84 if(Math.abs($twin.height()+lineHeight - $textarea.height()) > 3){
86 var goalheight = $twin.height()+lineHeight;
87 if(goalheight >= maxheight) {
88 setHeightAndOverflow(maxheight,'auto');
89 } else if(goalheight <= minheight) {
90 setHeightAndOverflow(minheight,'hidden');
92 setHeightAndOverflow(goalheight,'hidden');
102 $textarea.css({'overflow':'hidden'});
104 // Update textarea size on keyup
105 $textarea.keyup(function(){ update(); });
107 // And this line is to catch the browser paste event
108 $textarea.live('input paste',function(e){ setTimeout( update, 250); });
110 // Run update once when elastic is initialized