JavaScript - updating <textarea> value under certian conditions and append it to a <div>

Viewed 161

I have a pagaraph (p) appended to a div, that shows <textarea> value, and it works well.

The <textarea> supposed to be a part of a page that allows the users to add new lines to the text content, exactly like how we can type <br> for a new line in textarea.
But since they don't know how to do that I'm trying to make it easy for them by:

(typing plus sign twice ++ OR pressing Enter on the keyboard)

Both should add a <br> tag automatically while typing (onkeyup)...

var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;

textarea.onkeyup = function(){
    currentText = textarea.value;
    var previewAsString = "<p class='p-preview'>" + currentText + "</p>" 
    textareaPreview.innerHTML = previewAsString;
};
textarea {
  width: 300px;
  height: 80px;
  resize: vertical;
}
<div class="block">
    <textarea id="textarea" placeholder="Type here.."></textarea>
</div>

<div class="block">
    <div class="textarea-preview"></div>
</div>

1 Answers

It sounds like all you need is to replace ++ and newlines with <br>:

var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;

textarea.onkeyup = function(){
    currentText = textarea.value;
    var previewAsString = "<p class='p-preview'>" + currentText.replace(/\+\+|\n/g, '<br>') + "</p>" 
    textareaPreview.innerHTML = previewAsString;
};
textarea {
  width: 300px;
  height: 80px;
  resize: vertical;
}
<div class="block">
    <textarea id="textarea" placeholder="Type here.."></textarea>
</div>

<div class="block">
    <div class="textarea-preview"></div>
</div>

Related