-1

How can I make a textarea which does not force line wrapping and extends its size to match the contents instead of showing a scroll-bar?

I need a textarea with dynamic width. The width should be the widest line of the textarea. I mean there should be no wrapping and the width should be changed the long a line gets.

user3848987
  • 1,627
  • 1
  • 14
  • 31
  • I'm not sure what the question is here. you want a text area the full width of a window and you don't want the text to wrap? Sounds like you want a full width input box of type text (textbox). – jnoreiga Oct 27 '15 at 21:27
  • Do you want a text field to change size based off the amount of words typed in it? Have you tried anything, give us a sample of what you have researched and what you have tried. – Adam Buchanan Smith Oct 27 '15 at 21:30
  • I want to change the width of a textarea based of the amount of characters typed. So if I type a very long line, the textarea gets wider. I just find scripts and posts for dynamic height of textarea, but I need a dynamic width... – user3848987 Oct 27 '15 at 21:35
  • look at this post: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – Gregg Duncan Oct 27 '15 at 21:38

1 Answers1

3

Assign an input listener function which compares the scroll width and height against the outer width and height of the element. If they are different then set them as necessary.

For CSS you need white-space:nowrap to stop the lines from wrapping and overflow:hidden to get rid of the scroll bars.

$('.demo').on('input', function(e){
    this.style.width = '';
    this.style.height = '';
    if(this.scrollWidth > this.clientWidth) this.style.width = this.scrollWidth + 'px';
    if(this.scrollHeight > this.clientHeight) this.style.height = this.scrollHeight + 'px';
})
.demo {
  white-space: nowrap;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="demo"></textarea>