Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle oncut, oncopy, and onpaste in jQuery?

The jQuery documentation says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error.

I need to handle cut, copy, and paste events. How best to do that? FWIW, I only need to worry about WebKit (lucky me!).

UPDATE: I'm working on a "widget" in a Dashboard-like environment. It uses WebKit, so it only really matters (for my purposes) whether these events are supported there, which it looks like they are.

like image 226
Andrew Hedges Avatar asked Oct 26 '08 00:10

Andrew Hedges


2 Answers

You can add and remove events of any kind by using the .on() and off() methods

Try this, for instance

jQuery(document).on('paste', function(e){ alert('pasting!') }); 

jQuery is actually quite indifferent to whether the event type you assign is supported by the browser, so you can assign arbitrary event types to elements (and general objects) such as:

jQuery('p').on('foobar2000', function(e){ alert(e.type); }); 

In case of custom event types, you must .trigger() them "manually" in your code, like this:

jQuery('p').trigger('foobar2000'); 

Neat eh?

Furthermore, to work with proprietary/custom DOM events in a cross-browser compatible way, you may need to use/write an "jQuery event plugin" ... example of which may be seen in jquery.event.wheel.js Brandon Aaron's Mousewheel plugin

like image 51
Már Örlygsson Avatar answered Oct 18 '22 13:10

Már Örlygsson


Various clipboard events are available in Javascript, though support is spotty. QuicksMode.org has a compatibility grid and test page. The events are not exposed through jQuery, so you'll either have to extend the library or use native Javascript events.

like image 42
dansays Avatar answered Oct 18 '22 13:10

dansays