Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Building an AutoResizing TextArea that Doesn't Flash on Resize

I've been working to create an auto resizing textarea (like on FB) that resizes as you type. There are a few plugins out there. Problem is they all are only 99% there. What's missing is:

  • On Resize the textarea flashes (on return/enter)
  • On Paste there is a delay

Please take a look here: http://jsfiddle.net/uzjdC/3/

Any ideas why it flashes on resize? Type some text, then press Enter to see it..

Thanks

like image 248
AnApprentice Avatar asked Feb 26 '23 08:02

AnApprentice


1 Answers

Yahoo! I've found a solution! Your example intrigued me very much, that's why I decided to play around in jsFiddle to try to fix your flashing issue. The flashing is due to the fact that the TextArea has 'to much text' and some scrolling occurs. The keyup event isn't equipped to beat this scrollbar, but... the scroll event is!

Html:

<textarea id="tst" rows="1" cols="40">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum porttitor neque eget consequat. Sed faucibus purus vitae felis facilisis bibendum.</textarea>

Css:

textarea{    
    overflow:hidden;
    overflow-x:hidden;
    overflow-y:hidden;
    padding:10px;
}

To do the upsizing I'm using the rows attribute of the TextArea. I've written it into a function: I'm up-sizing the area with this function:

//resize text area
function resizeTextArea(elem){

    elem.height(1); 
    elem.scrollTop(0);
    elem.height(elem[0].scrollHeight - elem[0].clientHeight + elem.height());
}

Now we only need to bind the resize:

//inital resize - on document load
resizeTextArea($('#tst'));

//bind events
$('#tst').bind('scroll keyup', function(){
    resizeTextArea($(this));
});

Note: no flashing occurs! Why? Because the use of the scoll event! You can try the solution here: http://jsfiddle.net/KeesCBakker/2D8Kf/

Good luck!

Edit: Changed the code in the jsFiddle example to support schemes that have dynamicly added textareas. Check also this SO question.

like image 174
Kees C. Bakker Avatar answered Apr 28 '23 04:04

Kees C. Bakker