Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 15370  / 14 Years ago, tue, october 5, 2010, 12:00:00

In my application there are few <textarea> presents and applied pagination to all these <textarea>. On a page one <textarea> is displayed.



Assume there are 10 <textarea> exist, then there will be exist 10 pages, one <textarea> on each page.



I have applied auto fit feature to these <textarea>, written below function for this :



function resizeTextarea(id) {

var minHeight = 75px;
textareaObj = document.getElementById(id);

var scrollH = textareaObj.scrollHeight+'px';
if((textareaObj.style.height != scrollH) && (textareaObj.scrollHeight!=0)){
textareaObj.style.height = scrollH;
} else
{
textareaObj.style.height = minHeight;
}
}


I have called this function on some events in <textarea> element defination i.e. :



<textarea class=autoGrow onkeyup=resizeTextarea(this.id); onchange=resizeTextarea(this.id); onkeydown=resizeTextarea(this.id); onmouseup=resizeTextarea(this.id); onfocus=resizeTextarea(this.id); style=width:78%;height:75px;overflow:hidden onclick=resizeTextarea(this.id); rows=6 cols =80 id=input><?php echo decodeChars($textdata) ;?></textarea>


Auto fit feature works properly once user triggers above mentioned events, i.e. onchange,onkeyup,onkeydown.



I stuck to one main problem that, auto fit feature wont work once page get's load.



for this I have also added below code on document.ready i.e.



$(document).ready(function() {
if($('.autoGrow')) {
var setOfElement = $('.autoGrow');
for(var i = 1 ; i <= setOfElement.length ; i++) {
resizeTextarea(setOfElement[i].id);
}
}
});


Still facing same problem that, user explicitly needs to click or jumps to <textarea> to work my auto fit feature.



Please folks suggest me any pointers you have.



Your sugggestion will helps me lot.



Thanks



-Pravin


More From » jquery

 Answers
6

You could (with most of your current code so the calculations are the same) re-write it as a plugin, like this:



jQuery.fn.resizeTextarea = function(min) {
min = min || 75;
return this.bind(keyup change click focus, function() {
var sh = this.scrollHeight;
$(this).height(function(i, h) {
return h <= sh && sh != 0 ? sh : min;
});
}).trigger(keyup); //run it once immediately
};


Then in your document.ready handler, just call that on the elements you want, for example:



$(function() {
$('.autoGrow').resizeTextarea();
//or, as it's written you can pass a different minimum height, for example:
//$('.autoGrow').resizeTextarea(45);
});


You can test it out here.


[#95415] Friday, October 1, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;