Alex Rivera | Logout

Textarea resize

Asked 2011-04-02T12:30:39.680
11

I need to use a textarea to show some text. The problem is that if I place 4-5 rows of text a scrollbar will appear. How can I use CSS/HTML so that the textarea will be as large as it's content (no scrollbar).

  • the textarea doesn't need to change it's size dynamicaly, I use it only to show a text (I could also use a disabled textarea)

  • I want the textarea to stretch only verticaly.

If you want to know:
I use the textarea to show some text from a database, so when the textarea (with the text in it) is created, it should show the whole text at once with no scrollbars.

Edit
Report

1 Answer

12
<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
    border: 0 none white;
    overflow-y: auto;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
    resize: none;
}
</style>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init (maxH) {
        var text = document.getElementById('text');
    var maxHeight=maxH;
    var oldHeight=  text.scrollHeight;
    var newHeight;
    function resize () {

    text.style.height = 'auto';
    newHeight= text.scrollHeight;
    if(newHeight>oldHeight && newHeight>maxHeight  )
    {
        text.style.height=oldHeight+'px';

    }
    else{
        text.style.height = newHeight+'px';
        oldHeight=  text.scrollHeight;
    }

    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}
</script>
</head>
<body onload="init(200);">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>

http://jsfiddle.net/TDAcr/

answered 2012-10-13T17:39:38.273

Your Answer