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.
The paste event fires when the user initiates a paste action through the browser's user interface. The original target for this event is the Element that was the intended target of the paste action. You can listen for this event on the Document interface to handle it in the capture or bubbling phases.
The onpaste attribute lets us prevent pasting into the form. Adding the autocomplete attribute as well as preventing drag and drop into the element. If you want to avoid the on{event} code in the HTML, you can do it the cleaner way: myElement.
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:
setTimeout(sanitize, 0)
and from your sanitizing method:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With