Paste text only in editable div

I need to allow the user to paste into an editable div (through any user who chooses: right-click and paste, shortcut key, etc.), but I want to cancel the formatting and use only plain text.

I can’t use a text field since the div allows basic formatting (bold and italics) if it applies to user-initiated events.

the onbeforepaste event looked promising, but according to quirksmode, support is so limited that it cannot be used.

tyia for any suggestions

+4
source share
4 answers

It is difficult, but not impossible. What you can do is pretty hard and a bit of a hack that will work in Firefox 2+, IE 5.5+ and the latest WebKit browsers like Safari 4 or Chrome (unverified in older versions). Recent versions of TinyMCE and CKEditor use this technique in their iframe-based editors:

  • Detect ctrl-v / shift-ins event with a keystroke event handler
  • In this handler, save the current user selection, add the textarea element off the screen (say, left -1000px) to the document, include contentEditable and call focus () in the text field, thus moving the caret and effectively redirecting the paste
  • Set a very short timer (say, 1 millisecond) in the event handler to call another function that stores the textarea value, removes the text field from the document, turns on contentEditable again, restores the user's selection and inserts the text.

Please note that this will only work for keyboard insert events, and not from pastes in the context menu or in the edit menu. The paste event would be better, but by the time it fires, it’s too late to redirect the cursor to the text box (at least in some browsers).

+1
source

For Ctrl + v, I checked the contents of the editable div on the keyboard. You can change the contents of this event. I used the nicedit text editor. This does not work for paste with right click β†’ paste. For paste I had to change the contents using settimeout .

 .addEvent('paste', function(e) { setTimeout(function(){ if(condition){ //modify content } },350); }); 
+1
source

It can also be jailbroken using javaScript. Hope this helps

I created an example here

 <div contentEditable="true" id="clean-text-div"> </div> <div id="clean-btn"> Clean Me</div> <div id="message"> paste html content and clean background HTML for pure text</div> $("#clean-btn").click(function(){ $("#clean-text-div").text($("#clean-text-div").text()); $("#message").text("Your text is now clean"); }); 
+1
source

Have you tried an event like insert or enter? Then you can use regex to disable the whole html tag

 $(document).bind('paste', function(e){ alert('pasting!') }) 

http://www.hscripts.com/scripts/JavaScript/remove-html-tag.php

The insertion question you should also read is discussed:
Insert tab

0
source

All Articles