shabbir.rang
shabbir.rang

Reputation: 279

Prevent the horizontal expansion of text when being typed.Text can expand vertically

I have certain piece of code which enables me to type in textarea. I am increasing width of textarea on keypress and i am giving width a limit after which it should stop increasing. What i want is on width limit reach stop typing and when user press enter key start typing again.

Heres Sample code :

var maindivwidth = $('.maindiv').width();           
var vWidth = 0;
var hIncr = 2;   
var tWidth = $('textarea')[0].value.length;
var iheight = $(dividfortextbox).css('font-size').replace('px','');

$(dividfortextbox).keypress(function(e) {

if ((e.keyCode || e.which) == 13) {

$(this).parent(dividfortext).css('height', (hIncr * iheight) + 'px');
  vWidth = 0;
  hIncr++;
}
else 
{       
    vWidth = (vWidth+1);

 if (tWidth < maindivwidth-aminus && vWidth*9 > tWidth){
 tWidth = vWidth*9;
 $(this).parent(dividfortext).css('width', (tWidth) + 'px');

 }
 else{
    ??????????????????????????
 } 

 }
 });

Upvotes: 0

Views: 309

Answers (1)

Jonathan
Jonathan

Reputation: 2983

If I got you right, this may be what you're looking for: Auto grow text area (jsFiddle)

No need for the user to press enter here to continue writing, the textarea automatically expands vertically. Depending on the nature of your project, this - although far from perfect! - might very well do the job. Please note that this method requires jQuery, although obviously it can be done without it.

HTML

<div id="textareaContainer">
   <textarea id="expandTextArea"></textarea>
</div>

CSS

#expandTextArea {
padding:8px 1%;
height:20px;
width:160px;
font-size:16px;
color:#242424;
border:1px solid #333;

/*important for getting the smooth expansion effect*/
-webkit-transition: height 0.6s;
-webkit-transition-timing-function: height 0.6s; 
-webkit-transition: width 0.6s;
-webkit-transition-timing-function: width 0.6s;

overflow:hidden;
}

Jquery

$('textarea#expandTextArea').live('keydown', function() {

//insert your values here
var expandTextareaAfter = 20; //characters, grow horizontally
var breakRowAfter = 50; // characters, grow vertically
var fontSize = 16; //textarea fontsize in px

var ta = $("#expandTextArea");
var nrOfLetters = ta.val().length;
var newWidth = (nrOfLetters*9);

//check if textarea is full and expand the textarea horizontally/vertically
if ((nrOfLetters >= expandTextareaAfter) && (nrOfLetters <= breakRowAfter)) {
    ta.css("width", newWidth+"px");
} else if (nrOfLetters > expandTextareaAfter) {
    ta.css("height", ((fontSize+1) * (Math.round(nrOfLetters/breakRowAfter))) + "px");
}
});​

Upvotes: 1

Related Questions