article

Sunday, December 15, 2019

Auto Resize Textarea Height using jQuery

Auto Resize Textarea Height using jQuery
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auto Resize Textarea Height using jQuery</title> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
    var textArea = $('#content'),
    hiddenDiv = $(document.createElement('div')),
    content = null;
    
    textArea.addClass('noscroll');
    hiddenDiv.addClass('hiddendiv');
    
    $(textArea).after(hiddenDiv);
    
    textArea.on('keyup', function(){
        content = $(this).val();
        content = content.replace(/\n/g, '<br>');
        hiddenDiv.html(content + '<br class="lbr">');
        $(this).css('height', hiddenDiv.height());
    });
});
</script>
<style>
textarea{
  font-family: Arial, sans-serif;
  font-size: 13px;
  color: #444;
  padding: 5px;
}
.noscroll{
  overflow: hidden;
  resize: none;
}
.hiddendiv{
  display: none;
  white-space: pre-wrap;
  min-height: 50px;
  font-family: Arial, sans-serif;
  font-size: 13px;
  padding: 5px;
  word-wrap: break-word;
}
.lbr {
  line-height: 3px;
}
</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-9">
            <p><h1>Auto Resize Textarea Height using jQuery</h1></p>
   <textarea id="content" class="form-control"></textarea>
     </div>
   </div>
</div>

</body>
</html>

Related Post