Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 25674  / 13 Years ago, sat, november 19, 2011, 12:00:00

given a content editable div. How can I detect a paste event, prevent the paste from being inserted so can I can intercept and sanitize the paste to include text only?



I also don't want to lose focus after the paste + sanitize is complete.


More From » jquery

 Answers
6

UPDATE:



All major browsers now give you access to the clipboard data in a paste event. See Nico Burns's answer for an example on newer browser and also check out Tim Down's answer if you need to support older browsers.






You can listen for the onPaste event on the div to detect the paste. If you just want to disable the paste you can call event.preventDefault() from that listener.



To capture the pasted content however is a little bit more difficult since the onPaste event does not give you access to the pasted content. The usual way to handle this is to do the following from the onPaste event handler:




  • create a dummy div and place it outside the window boundaries so it's not visible to visitors

  • move the focus to this div

  • call a sanitizer method using a setTimeout(sanitize, 0)



and from your sanitizing method:




  • find the dummy div and get it's contents

  • sanitize the HTML and remove the div

  • move the focus back to the original div

  • insert the sanitized content in the original div


[#89022] Friday, November 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;