I want to make a dynamic textarea, it should increase in rows as the content increase.
I am using this code:
$("#text_textarea").keyup(function(e) {
//splitting textarea value wrt '\n' to count the number of lines
if ($(this).val().lastIndexOf('\n')!=-1)
var x = $(this).val().split('\n');
$(this).attr( "rows" , x.length+1 );
});
But it fails when user continues to write without giving any new line \n (pressing Enter).
var keyUpTimeout = false; // Required variables for performance
var keyupTimer = 0;
$("#text_textarea").keyup(function(e) {
var cooldownTimeout = 500;
//Set the cooldown time-out. The height check will be executed when the user
// hasn't initiated another keyup event within this time
var ths = this;
function heightCheck(){
keyupTimer = false;
// Reset height, so that the textarea can shrink when necessary
ths.style.height = "";
// Set the height of the textarea
var newheight = this.scrollHeight + 2;
ths.style.height = newheight + "px";
}
if(keyupTimeout){ //Has a cooldown been requested?
clearTimeout(keyupTimer); //This+next line: Refresh cooldown timeout.
keyUpTimer = setTimeout(heightCheck, cooldownTimeout);
return; //Return, to avoid unnecessary calculations
}
// Set a cooldown
keyupTimer = setTimeout(heightCheck, cooldownTimeout);
keyupTimeout = true; //Request a cooldown
});
This piece of script will change the height of the textarea to fit the text inside.
Update
I have added an additional feature: To improve performance (changing the CSS height requires a significant amount of computer power), I have added a cooldown effect: The height check will only be executed when the user hasn't initiated a keyup event for 500 milliseconds (adjust this value to meet your wishes).
read this,
Textarea Height increase
TextAreaExpander (Demo)
autoResize Plugin
JQuery Elastic
You should use the attribute wrap='hard' on your textarea.
I write this code. what about it..
$("#text_textarea").keyup(function(e) {
var textarea_height = Number($(this).css('height').replace("px", ""))+4;
var scroll_height = this.scrollHeight;
if(textarea_height < scroll_height ){
$(this).css('height' ,"");
var x = Number(scroll_height) + 3;
if(x != $(this).height())
$(this).css("height", x+"px");
}
});
Related
I wrote a html/php page in order to update database content. The page has several forms (one for each db row I need to edit), and every form has several textarea fields.
I would like to fit every textarea's height to its content (as retrieved from db), using pure JavaScript (no jQuery).
I've found the following JS function:
function autoResize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
But how can I use it for every textarea field in the page? Is there a better way to achieve the goal?
Thanks!
UPDATED
Maybe this is a good solution:
var els = document.querySelectorAll('textarea');
Array.from(els).forEach((el) => {
var offset = el.offsetHeight - el.clientHeight;
el.style.height = 0;
el.style.height = el.scrollHeight + offset + 'px';
el.addEventListener('input', function() {
el.style.height = el.scrollHeight + offset + 'px';
});
});
Could it be done in a better way?
Check out this snippet:
<script>
var content = document.getElementsByClassName('db-content');
for(var i=0; i<content.length; i++){
content[i].style.height = 'auto';
content[i].style.height = content[i].scrollHeight + 'px';
}
</script>
You have to apply same class to all <textarea> (db-content in the above snippet) and add this script after them. In the script we are looking for all of those <textarea> by their class name and storing them in an array. Next we loop through the array and apply style to all <textarea>.
I'm trying to make the elements on the page fade in on scroll. Easy enough right? Not for me.
HTML is a standard list.
CSS sets all elements to opacity 0 prior to scrolling.
I'm trying to use Native JavaScript only.
// get current page body
var actBody = document.getElementById('acts-body');
// on scroll function
actBody.onscroll = function(){
// get screen height
var screenPosition = window.innerHeight;
// get all text elements
var artistName = document.getElementsByClassName('artist');
// loop through all elements
for(var i = 0; i < artistName.length; i++){
// get each elements position from top
var positionFromTop = artistName[i].getBoundingClientRect().top;
// if element is in viewport add class
if(positionFromTop - screenPosition <= 0){
artistName[i].classList.add('txt-fadeIn');
}
else{
artistName[i].classList.remove('txt-fadeIn');
}
console.log(artistName[i]);
}
i think it should solve it
if(screenPosition - positionFromTop <= 0){
artistName[i].classList.add('txt-fadeIn');
}
I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.
Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.
Any ideas? Gracious !!!
Edit by XeeMez:I've modified the code a little because it was acting a little odd, I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.
resizeIt = function( ) {
var str = $( 'iso_address' ).value;
var cols = $( 'iso_address' ).cols;
var linecount = 0;
$A( str.split( "\n" ) ).each( function( l ) {
linecount += 1 + Math.floor( l.length / cols ); // take into account long lines
} )
$( 'iso_address' ).rows = linecount;
};
Here's technique for autosizing a textarea.
Uses pixel height instead of line height: more accurate handling of line wrap if a proportional font is used.
Accepts either ID or element as input
Accepts an optional max height param - useful if you'd rather not let the text area grow beyond a certain size (keep it all on-screen, avoid breaking layout, etc.)
Tested on Firefox 3 and IE6
Code: (plain vanilla Javascript)
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if ( !text )
return;
/* Accounts for rows being deleted, pixel value may need adjusting */
if (text.clientHeight == text.scrollHeight) {
text.style.height = "30px";
}
var adjustedHeight = text.clientHeight;
if ( !maxHeight || maxHeight > adjustedHeight )
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if ( maxHeight )
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ( adjustedHeight > text.clientHeight )
text.style.height = adjustedHeight + "px";
}
}
Demo: (uses jQuery, targets on the textarea i'm typing into right now - if you have Firebug installed, paste both samples into the console and test on this page)
$("#post-text").keyup(function()
{
FitToContent(this, document.documentElement.clientHeight)
});
Here is the approach I used.
Call expandTextArea on keyup or keypress.
var minimumTextAreaRows = 10;
function expandTextArea(event) {
var element = event.target;
element.rows = minimumTextAreaRows;
while (element.clientHeight < element.scrollHeight) {
element.rows = element.rows + 1;
}
};
Combine with a css that prevents the scrollbar to avoid it flashing
textarea.noscrollbar {
overflow: hidden;
}
This will also "shrink" to the minimum size you specify. Remove element.rows = minimumTextAreaRows; to make it not shrink.
I have a text area box that expands from 3 to 17 rows when the user enters so many characters as well as on a button click.
SetNewSize(); function is the called via onkeyup and expands the text area when the length becomes greater than 50.
morespace(); function is called via the button.
I would like to slide the box out when this happens, any ideas?
Thanks here is my code:
function SetNewSize(textarea){
if (textarea.value.length > 50)
{
textarea.rows = 17;
}
else
{
textarea.rows = 3;
}}
function morespace(){
var thetxt = document.getElementById('more').value;
var box = document.forms["myForm"]["comment"];
if(box.rows == 3)
{
$("#emailme").fadeOut(800);
box.rows = 17;
document.getElementById('more').innerHTML = "less space?";
}
else
{
$("#emailme").fadeIn(800);
box.rows = 3;
document.getElementById('more').innerHTML = "more space?";
}}
By "slide the box out", I'm guessing you mean animate it. While you may not be able to animate textarea rows in jQuery, you can animate the height of the textarea to give the user more room. For example, you trigger something like this:
$('#comment').animate({'height': '+=40'},200);
This will add 40 pixels of height every time it is triggered and it animates it smoothly. If you want to add a number rows, you could simply calculate how large you want the textarea to become and then animate it to that height.
Here's a JSFiddle link for this action and you may want to check out the jQuery animate API.
Well, the quick answer is use something someone already made: https://github.com/gurglet/jQuery-Textarea-Autoresize-Plugin
But if you want to roll your own, I'll update my reply in a moment with the code you need.
Updated Answer:
Assuming you have this HTML:
<button id="emailme">Email me</button>
<form id="myForm">
<input id="more" name="more" type="text">
<textarea id="comment" name="comment" rows="3">
</textarea>
</form>
You could then use this script:
(function(){
var BIG = 17,
SMALL = 3,
currentSize = SMALL,
changeSize = function(rows) {
var $more = $("#more"),
thetxt = $more.val(),
$box = $("#comment"),
currentRows = $box.prop("rows"),
boxRowHeight = $box.height()/currentRows,
newHeight = rows * boxRowHeight;
if (rows === currentRows) return;
return $box.animate({'height': newHeight }, 500 , "swing", function(){
$more.val((currentRows > rows) ? "more space?" : "less space?");
$box.prop("rows", rows);
currentSize = rows;
}).promise();
},
setNewSize = function(event) {
var $area = $(event.target);
if ($area.val().length > 50 && currentSize === SMALL) {
changeSize(BIG);
currentSize = BIG ;
}
};
$("#comment").bind("keyup", setNewSize);
$("#more").click(function(){
if (currentSize === BIG) {
$.when(changeSize(SMALL)).then(function(){
$("#emailme").fadeIn(800);
});
}else{
$.when(changeSize(BIG)).then(function(){
$("#emailme").fadeOut(800);
});
}
});
})();
JSFiddle Link: http://jsfiddle.net/isochronous/fvtY7/
You could also use jquery's attr() like so:
$('#comment').attr('rows', 17);
Where rows represent the attribute to cahnge and 17 the value to set.
To get the number of rows currently used you use:
var rows = $('#comment').attr('rows');
I set the width of a textarea to 100%, but now I need to know how many characters can fit in one row.
I'm trying to write a javascript function to auto-grow/shrink a textarea. I'm trying to keep from using jquery since I just need this one function.
My logic is to rows = textarea.value.split('\n'), iterate through rows and count += rows[i].length/textarea.cols, then count += rows.length, and finally textarea.rows = count. The only problem is that count is too large because textarea.cols is too small.
This function will set the height of the element (textarea, in your case) to the browser's default height. If that causes a scrollbar to appear, the height will be switched to the actually needed height.
function autoHeight(element){
element.style.height='auto';
element.style.height=element.scrollHeight+'px';
}
If you don't like the browser's default height, you can change that to some other default value of your own, of course.
Try this and enjoy:
var textarea = document.getElementById("YourTextArea");
var limit = 50; //height limit
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, limit) + "px";
};
textarea {
width: 99%;
}
<textarea id="YourTextArea"></textarea>