online Thomas
online Thomas

Reputation: 9391

How to keep the text formatting on pasting in jQuery?

I'd like to edit the text before it is pasted.

My current code is:

element.on('paste', function (event) {
    event.preventDefault();
    var clipboardData = (event.originalEvent || event).clipboardData;
    var text = clipboardData.getData('text/html') || clipboardData.getData('text/plain') ||
    //document.execCommand('insertHTML', false, text);  <--     
});

I used this first but it sometimes fails and malforms the text formatting which I want to keep.

I think that using another function than execCommand will fix this bug, because I read more people are having trouble with this function and it has very limited support

Upvotes: 1

Views: 2012

Answers (1)

Alexander Elgin
Alexander Elgin

Reputation: 6956

element.on('paste', function (event) {
  event.preventDefault();
  var clipboardData = (event.originalEvent || event).clipboardData;
  var text = clipboardData.getData('text/html') || clipboardData.getData('text/plain') ||
  document.execCommand('insertHTML', false, '<pre>' + text + '</pre>');
});

Upvotes: 1

Related Questions