25

How can I handle the paste selected through right click in JavaScript? I tried with onpaste event and all other html events available but nothing works.

1
  • Have you tried the suggested solutions? Commented Jun 1, 2012 at 11:59

4 Answers 4

31

The onpaste event should work in all modern browsers (UPD Including Opera >= 12.101).

Bind it in jQuery like this:

$('#txt').on('paste', function() {console.log('text pasted!')})​ 

Here's a live example: http://jsfiddle.net/7N6Xq/

In pure JavaScript it would look something like this for modern browsers

elem.addEventListener ("paste", handler, false); // all browsers and IE9+ 

and for old IE versions:

elem.attachEvent ("onpaste", handler); // IE<9 

You can also combine it with oninput and other events (change, propertychange, dragdrop, etc.) to create a relatively bulletproof tracking of content change.


Footnotes:

1 Opera supports Clipboard API starting from Presto/2.10.286 which corresponds to 12.10 as suggested here. Blink versions of Opera (starting from 15) should also support it but I am unable to test it as there is still no Linux version.

Sign up to request clarification or add additional context in comments.

Comments

2

The event isn't exposed by default as "onpaste" IIRC. You can do it quite simply in jQuery by issuing

jQuery(document).bind('paste', function(e){ alert('paste event caught') }); 

1 Comment

Paste event is captured but contents can't be read this way, like "document.addEventListener" can.
1

I was surprised question #4532473 got closed unanswered about what happens if you want to capture the afterpaste event. As this is probably the problem half of the cases a possible approach in firefox (tested) is to register an oninput event right inside the onpaste handler and remove the oninput handler as soon as it's done executing.

In ie the onpropertychange should be used instead of oninput. (not tested)

1 Comment

For those interested, a simple implementation of an afterpaste
1

Nice pure JS solution (as requested...) is available on the Mozilla dev site

<!DOCTYPE html> <html> <head> <title>onpaste event example</title> </head> <body> <h1>Play with this editor!</h1> <textarea id="editor" rows="3" cols="80"> Try pasting text into this area! </textarea> <script> function log(txt) { document.getElementById("log").appendChild(document.createTextNode(txt + "\n")); } function pasteIntercept(evt) { log("Pasting!"); } document.getElementById("editor").addEventListener("paste", pasteIntercept, false); </script> <h2>Log</h2> <textarea rows="15" cols="80" id="log" readonly="true"></textarea> </body> </html> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.