0

I have a content-editable div that's being used like a text area element (I can't use an actual text area because I need rich text capabilities). When I copy and past multiple lines of text into it, the default behavior creates a mess of nested divs which makes it a lot harder to do things such as getting the actual text content of the div.

I found a solution for this problem here

editor.addEventListener("paste", function(e) {
    // cancel paste
    e.preventDefault();

    // get text representation of clipboard
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    // insert text manually
    document.execCommand("insertHTML", false, text);
});

However, this uses the deprecated execCommand. Should I just use execCommand or is there am easy way to do this with supported code.

Cooper M
  • 3
  • 1
  • have you read the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event) about the paste event already? – tacoshy Aug 14 '23 at 05:41
  • Yes I understand what to do there I just don't know how to format what has been copied to the clipboard and then insert it into the div correctly. – Cooper M Aug 14 '23 at 05:47

1 Answers1

0

I created a JSFiddle for you that should do what you want.

 var editor = document.querySelector('.editor');

        editor.addEventListener("paste", function(e) {
            e.preventDefault();

            var text = (e.clipboardData || window.clipboardData).getData('text/plain');
            var selection = window.getSelection();
            if (!selection.rangeCount) return;

            var range = selection.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(text));
        });
  1. Prevent the default paste behavior using e.preventDefault().
  2. Get the plain text content from the clipboard using the correct API for different browser contexts (e.clipboardData for modern browsers and window.clipboardData for older ones).
  3. Get the current selection and its range.
  4. Delete the contents within the range.
  5. Insert a new text node with the clipboard text content.

This approach avoids the use of execCommand and instead directly manipulates the DOM using more up-to-date methods.

stax
  • 132
  • 8
  • which is a copy of the linked documentation and proves that the OP didn't read the documentation or at least didn't copy the code. However, you should use `let` instead of `var`, unless you know and understand the difference! – tacoshy Aug 14 '23 at 06:43
  • This code is in fact from the documentation you listed earlier. Maybe he just needed an working example with code in action for better understanding. And yes I agree with you, `let` would be more appropriate. – stax Aug 14 '23 at 07:05