Working example of plaintext contenteditable

Plain text contenteditable using clipboard API. This is working in almost every browser.

by marinagon

HTML

<div class="text-to-copy">
  <h2> Copy this...</h2>
  <img src="http://www.cupcakeipsum.com/assets/green_muffin.png">
  <p>
    Cupcake ipsum dolor sit amet gummi bears pastry I love apple pie. I love gummi bears cake biscuit. Sugar plum topping croissant.
  </p>
  <p>
    Toffee macaroon croissant halvah bonbon sugar plum caramels. Chocolate cake gummies powder cake tart tart. Dessert cake toffee. Brownie gummi bears croissant pie.
  </p>
</div>

<div contenteditable class="plaintext">
  <p> Paste text here... </p>
</div>

CSS

div[contenteditable] {
  position: relative;
  width: 50%;
  display: inline-block;
  background: #fff;
  min-height: 200px;
  border: 1px solid #1d3049;
  outline: none;
  font-size: 16px;
  color: #000!important;
}

.text-to-copy {
  background-color: darkgrey;
  width: 40%;
  float: left;
}

JavaScript

function insertTextAtCursor(text) {
  var sel, range, html;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      range.insertNode(document.createTextNode(text));
    }
  } else if (document.selection && document.selection.createRange) {
    document.selection.createRange().text = text;
  }
}


document.querySelector(".plaintext[contenteditable]").addEventListener("paste", function(e) {
  e.preventDefault();
  if (e.clipboardData && e.clipboardData.getData) {
    var text = e.clipboardData.getData("text/plain");
    document.execCommand("insertHTML", false, text);
  } else if (window.clipboardData && window.clipboardData.getData) {
    var text = window.clipboardData.getData("Text");
    insertTextAtCursor(text);
  }
});