Reputation: 9293
Click on ŞHOW / HIDE
several times.
You'll see that after each click textarea becomes more and more higher.
What is the reason and how to avoid this.
I need the textarea always to fit the content.
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
let a = $('#txa').prop('scrollHeight');
$('#txa').height(a);
});
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidde;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa'>
lorem ipsum
lorem ipsum
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
Upvotes: 0
Views: 60
Reputation: 1382
Please try this.
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
});
autosize();
function autosize(){
var text = $('#txa');
text.each(function(){
$(this).attr('rows',1);
resize($(this));
});
text.on('input', function(){
resize($(this));
});
function resize ($text) {
$text.css('height', 'auto');
$text.css('height', $text[0].scrollHeight+'px');
}
}
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa' name="md-content">
lorem ipsum
lorem ipsum
sdf
sdf
sdf
sdf
sdf
sdf
s
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
Upvotes: 1
Reputation: 185
Remove the following 2 lines from your script
let a = $('#txa').prop('scrollHeight');
$('#txa').height(a);
It still works and does not add an extra line in the textarea field.
Upvotes: 0
Reputation: 973
Here you go, the height manipulation was unnecessary.
$('#btna').on('click', function(){
$('#txa').hide()
});
$('#btnb').on('click', function(){
$('#txa').show()
});
#txa, #txb{
display:block;
width:100%;
resize:none;
overflow:hidde;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id='txa'>
lorem ipsum
lorem ipsum
</textarea>
<button id='btnb'>SHOW</button>
<button id='btna'>HIDE</button>
Upvotes: 0