How to paste rich text from clipboard to HTML text area element?

Sometimes, we want to paste rich text from clipboard to HTML text area element.

In this article, we’ll look at how to paste rich text from clipboard to HTML text area element.

How to paste rich text from clipboard to HTML text area element?

To paste rich text from clipboard to HTML text area element, we can listen for the paste event and put the pasted content in a contenteditable element.

For instance, we write:

<div id="target" contenteditable></div>

to add a contenteditable div.

Then we write:

document.addEventListener('paste', (e) => {
  e.preventDefault();
  let pastedText = ''
  if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/html');
  }
  document.getElementById('target').innerHTML = pastedText
});

We call document.addEventListener with 'paste' to listen for the paste event on the browser window.

We call it with a callback that calls e.preventDefault to prevent the default behavior,

And then we call e.clipboardData.getData to get the pasted data.

And we set the HTML content of the contenteditable div with:

document.getElementById('target').innerHTML = pastedText

As a result, we see the pasted text has the styles preserved.

Conclusion

To paste rich text from clipboard to HTML text area element, we can listen for the paste event and put the pasted content in a contenteditable element.