0

I'm currently working on a WYSIWYG text editor but having a little trouble with one element. Whenever I copy and paste text from a site it will paste with the background color too. I want it so that when it pastes the text, the background color is removed.

Currently I've got a div that can be edited:

<div id="editor" class="comment-section" contenteditable="true" spellcheck="false" tabindex="0"></div>

and then using jQuery I am trying to remove the background color of all children within the div as when I paste text it adds a span to the div:

$('#editor').on('paste', function(e) {
    $(this).children().attr('background-color', 'transparent');
});

But this seems to set the background color of the previous pasted text to transparent but still it doesn't actually remove the background.

TheWelshManc
  • 495
  • 3
  • 13

1 Answers1

1

Similar to the second solution from here: JavaScript get clipboard data on paste event (Cross browser)

$('#editor').on('paste', function(e) {
    let  pastedData, text;
    // Stop data actually being pasted into div
    e.stopPropagation();
    e.preventDefault();
    // Get pasted data via clipboard API
    pastedData = e.originalEvent.clipboardData || window.clipboardData;
    pastedData = pastedData.getData('Text');
    text = $(this).text();
    console.log(text, pastedData);
    $(this).text(text+pastedData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor" class="comment-section" contenteditable="true" spellcheck="false" tabindex="0"></div>
Gaurav Punjabi
  • 153
  • 1
  • 6
  • This works but it puts the cursor to the start of the text not the end and if I add a new line or make a space in the text box it deletes it – TheWelshManc Feb 09 '20 at 22:34
  • For the cursor: https://stackoverflow.com/questions/2871081/jquery-setting-cursor-position-in-contenteditable-div And I'm not getting the same issue when adding a new line or making a space, it's working fine. @TheWelshManc – Gaurav Punjabi Feb 09 '20 at 22:38
  • I don't know why it's causing this problem, I have other scripts working on the page but none of them are called when I use the paste function. I also removed all other scripts and it still does it. – TheWelshManc Feb 09 '20 at 23:04
  • Managed to get it to work properly by using ```document.execCommand('inserttext', false, pastedData);``` instead of ```$(this).text(text+pastedData);```. – TheWelshManc Feb 09 '20 at 23:24
  • Great! @TheWelshManc I couldn't really replicate the error in the online editor or I would have helped ya out there. – Gaurav Punjabi Feb 10 '20 at 05:25