How can I type in a textarea and have that text be added to a contenteditable div?

Tags: , , , ,



I have a <div contenteditable="true"> and a <textarea> on my page. I need to get the text that is typed in the textarea to be displayed in the div, while keeping the text that was already in the div. I already kind of achieved that with a keyup function on the textarea but it is not working properly. I believe the problem must be having the contenteditable text variable updated with each keyup. I tried changing the scope of value1, making it a global variable instead, but it still does not work. Any help?

This is my code:

JSFiddle

$(".secondary").keyup(function () {
  var value1 = $(".original").html();
  var value2 = $(".secondary").val();
  $(".original").html(value1 + value2);
});
div {
  width: 300px;
  height: 100px;
  border: solid 1px #000;
  overflow-y: scroll;
}

textarea {
  width: 300px;
  height: 100px;
  border: solid 1px #000;
  resize: none;
  overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Content Editable:</p>
<div class="original" contenteditable></div>

<br><br>

<p>Text Area:</p>
<textarea class="secondary"></textarea>

So, if you type “Foo” in the contenteditable and “bar” in the textarea, the text in the contenteditable should be “foobar”.

Also, if the last character in the contenteditable is a space, typing in the textarea will add a <br> to the contenteditable. Is there a way to fix that?

Answer

Instead of using keyup, I’d prefer to use input event handler. Try out the snippet :

$(".secondary").on('input', function(event) {
  var val = $('.original').text();
  $('.original').text(val + event.originalEvent.data);
});
div {
  width: 300px;
  height: 100px;
  border: solid 1px #000;
  overflow-y: scroll;
}

textarea {
  width: 300px;
  height: 100px;
  border: solid 1px #000;
  resize: none;
  overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Content Editable:</p>
<div class="original" contenteditable></div>

<br><br>

<p>Text Area:</p>
<textarea class="secondary"></textarea>


Source: stackoverflow