Reputation: 1037
I am try to duplicate fb like comment box , where they resize as text fills it using Expanding Text Areas Made Elegant
My view looks like:
<div class='expandingArea'>
<pre><span></span></pre>
<textarea id="comment_body" name="comment[body]" placeholder="In my opinion...">
</textarea>
</div>
<input class="comment_submit" name="commit" type="submit" value="Create Comment" />
my jquery is:
$( document ).ready(function() {
$('div.expandingArea').each(function() {
var area = $('textarea', $(this));
var span = $('span', $(this));
area.bind('input', function() {
span.text(area.val());
$(".comment_submit").css({"margin": "0.25em 0"});
$(".expandingArea.active textarea").css({"padding": "5px", "height": "95%"});
});
span.text(area.val());
$(this).addClass('active');
});
});
As user fills in data, the text area height increases and everything is fine. Then to submit he clicks on submit
button, which makes an ajax call, entered data gets stored in database and I reset the content of text area with:
$('textarea').val('');
But I need to set the height of text area back to it's origin height(When user enter text, its height was increased as text filled it). I can't use something like:
$('textarea').height(10);
As that will add height = 10px
to element style of textarea and then my resizing of textarea when user enters data in textarea won't work.Does anyone know how can I undo that resizing of textarea?
Further, if user types something in textarea after submitting then textarea resizes to normal size on it's own. I guess that triggers input
binded with textarea. So faking user input sort of thing can also work, but I don't know how to do it either.
Upvotes: 2
Views: 4109
Reputation: 1251
$("#comment_body").css("height", "50px"); // 50px - your default size.
Thanks Adriano Godoy
Upvotes: 0
Reputation: 1568
try:
$( document ).ready(function() {
$('div.expandingArea').each(function() {
var area = $('textarea', $(this));
var span = $('span', $(this));
area.bind('input', function() {
span.text(area.val());
area.attr('rows', 10);
});
span.text(area.val());
$(this).addClass('active');
});
$('.comment_submit').click(function() {
$('#comment_body').attr('rows', 2).val('');
});
});
JSFiddle: http://jsfiddle.net/ronqt8mc/
Upvotes: 0
Reputation: 27630
You bind the function that does the resizing on the input
event. When you empty the textarea it updates the value, but the event isn't triggered yet. One way to force the event is:
$('textarea').val('').trigger('input');
Example: jsfiddle
Upvotes: 2