0

Hey Stackoverflow comunity,

I have written an example code that should clean HTML code on paste, but it is not working as expected. On every paste it's duplicating the <textarea> and paste is not working.

Here is the JsFiddle: http://jsfiddle.net/Kxmaf/214/

Any help is much appreciated :)

Tim Down
  • 318,141
  • 75
  • 454
  • 536
Aley
  • 8,540
  • 7
  • 43
  • 56

1 Answers1

0

New Version : http://jsfiddle.net/Kxmaf/218/

You were right about setTimeout(), didn't know about the paste event latency. Now, I saw on FF, that document.execCommand() is kinda buggy, so I simplified it a lot (no more focus, execCommand):

$editor.on('paste, keydown', function() {
    var $self = $(this);            
    setTimeout(function(){ 
        var $content = $self.html();             
        $clipboard.val($content);
    },100);
});

How about this : http://jsfiddle.net/Kxmaf/215/

$editor.on('paste, keydown', function() {
     var $self = $(this),
         $content = $self.html();       
     $clipboard.val('').focus();
     document.execCommand('insertHTML', false, $content);
     $self.html($content);
     placeCaretAtEnd($self);                
});

No more setTimeout(). I added keydown too as it sounded better to me ;) You can delete it if you will. This does :

  • takes the content of #content
  • delete textarea content and focus on it.
  • insert the content from #content to the textarea
  • replace #content's content in case it cames deleted or replaced (it was part of my test, I don't know if $self.html($content); is relevant now.
  • focus with caret at the end of #content.

placeCaretAtEnd() comes from https://stackoverflow.com/a/4238971/460368 which I modified a little.

Community
  • 1
  • 1
Shikiryu
  • 10,180
  • 8
  • 49
  • 75
  • Unfortunately your example is not working. Its placing the content into the textarea, but not into the editable div :( The textarea is just a helper, which should catch the focus on 'paste' and clear the input and than place the content back into the div. – Aley Jul 02 '12 at 09:58
  • The new code isn't working too :( What the script should do is cleaning the clipboard content. On paste the textarea should catch the focus. The browser paste the content into the textarea. After 100 ms the cleaned content in the textarea should be copied back to the editable div. – Aley Jul 02 '12 at 14:12