Search code examples
javascripttextareamouseeventkeyboard-eventstextselection

Copying text from one textarea element to another in real-time


I want to copy input from one textarea to another textarea in real-time. This is not a HTML editor or rich text editor. Just plain simple text without any markup.

This is what I am doing:

a. I can detect the point at which the cursor was clicked in the source text area using the following (on mouseup)

 $("#txt1")[0].selectionStart)

b. I can detect the text selection using selectionStart and selectionEnd properties on mouseup. This allows me to keep track of delete to be reflected in the other textarea. That is if delete is the key pressed, and a selection was made I know what was deleted to be relected in the target text area.

c. Where I am stuck is the simple issue of new characters entered. I think keeping track of key pressed would be the inefficient approach as I would have to check if control, alt, shift keys, among others were also held down. Besides there is the issue of repeatedy keys presses. The efficient way is possibly to get the characters actually entered from the source text area and NOT based upon key pressed.

Questions: How do I get characters entered in the source textarea?

Is there a better way to update the target textarea in real-time? One way will be to continually update the content from the source to the target at regular interval but that would be inefficient. Any other approach?

I am open to using a contentEditable div in place of a textarea.

I need a solution that can work across different device types.


Solution

  • How do I get characters entered in the source textarea?

    Just handle the input event of the first textarea and make the second textarea have the same value as the first.

    let two = document.getElementById("two");
    document.getElementById("one").addEventListener("input", function(){
      two.value = this.value;
    });
    <textarea id="one"></textarea>
    <textarea id="two"></textarea>