Reputation: 1841
This is could be a very basic question, as what I'm wishing for here doesn't seem that crazy -- I looked throughly for some existing answer or better solution to this already, so I apologize in advance if this is any form of duplicate!
My question regards append()ing data to an existing textarea element:
jSFiddle: https://jsfiddle.net/natureminded/7w3rmggp/
My HTML:
<textarea id='chat'></textarea>
My JS/jQuery:
//note: 'chatMsg' data is provided back from the server
$('#chat').append(chatMsg.name+': '+chatMsg.message+' ');
$('#chat').scrollTop($('#chat')[0].scrollHeight); // focuses on bottom of textarea
My desired output: New lines append to the textarea, each new message as a new line. No extra lines at the bottom of the texarea.
What I'm experiencing: Indeed, new lines append to the textarea, each as a new line (due to the use of the
HTML carriage return). However, because of this new line character being at the end of my append()
string, a blank line is added beneath my last message (see: https://biturl.io/VCjaj5 for a screenshot). Adding the carriage return to the front of the string would fix the extra line break at the bottom, but would create a line break at the very top when the first message is sent.
I understand another way to approach this is by grabbing the .val()
of $('#chat')
, adding my new data as a new line, such as:
var oldChat = $('#chat').val();
var newChat = oldChat + ' ' + chatMsg.name + ': ' + chatMsg.message;
$('#chat').val(newChat);
However, when I try this approach, hoping to add the new message as a new line beneath the oldChat
, the HTMl carriage characters do not display and instead show as text (see: https://biturl.io/VCjmZ3). I also tried using the \n
character but this actually killed my javascript prompt
(not shown) and my chat broke.
Is there some better way to add new lines to my chat while not ending up with an extra white space at the bottom?
Note: Another possible solution I thought of was to try and somehow use regex to grab the last line and remove it, but I thought I would ask here if there was a simpler way to do this, or if I'm being too picky wanting my textarea to append text nice and clean (no extra line breaks).
Upvotes: 0
Views: 1803
Reputation: 2324
Try this:
var strt = $('#chat').text().replace(/[\s\r\n\t]/g,"").length == 0 ? "" : "
";
$('#chat').append(strt + chatMsg.name+': '+chatMsg.message);
scenario: detect if #chat
has messages append break line + message
if #chat
hasn't append only message.
Upvotes: 0
Reputation: 1256
You could have the newLine BEFORE instead of after, and in order to make sure there's no new line above the very first line, check if the textarea is empty.
so (pesudo code here but hopefully you get the idea)
string = chatmessage
// Prepend newline to string if the textarea already contains content
if textarea.value.length !== 0
string = ' ' + string
textarea.value = string
Upvotes: 2