Creative Enemy
Creative Enemy

Reputation: 398

Textarea height increase based on content height

I need increase the text area height based on content. if user type the content it automatically increase. and if delete the content it need reduce the height.

Upvotes: 1

Views: 1864

Answers (3)

Nishit Maheta
Nishit Maheta

Reputation: 6031

you can use jquery autogrow pluing

Code :

 $('textarea').autogrow({onInitialize: true});

Note : you need to include autogrow plugin file in to page

Upvotes: 1

Creative Enemy
Creative Enemy

Reputation: 398

Yes i got the answer, its work fine.

<textarea onkeyup="textAreaAdjust(this)" placeholder="Add a new answer" rows="1"></textarea>


 <script type="text/javascript"> 
                     function textAreaAdjust(o) {  
                     o.style.height = "1px";     o.style.height = (25+o.scrollHeight)+"px"; }
  </script>

Upvotes: 2

Ganesh Salunkhe
Ganesh Salunkhe

Reputation: 598

Try This:

<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 () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 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>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>

Here is Demo

Reference Creating a textarea with auto-resize

Upvotes: 1

Related Questions