Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery bind to Paste Event, how to get the content of the paste

I have a jquery token tagit plugin and I want to bind to the paste event to add items correctly.

I'm able to bind to the paste event like so:

    .bind("paste", paste_input)

...

function paste_input(e) {
    console.log(e)
    return false;
}

How can I obtain the actual pasted content value?

like image 942
AnApprentice Avatar asked Jul 23 '12 01:07

AnApprentice


4 Answers

There is an onpaste event that works in modern day browsers. You can access the pasted data using the getData function on the clipboardData object.

$("#textareaid").bind("paste", function(e){
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    alert(pastedData);
} );

Note that bind and unbind are deprecated as of jQuery 3. The preferred call is to on.

All modern day browsers support the Clipboard API.

See also: In Jquery How to handle paste?

like image 177
jeff Avatar answered Oct 12 '22 11:10

jeff


How about this: http://jsfiddle.net/5bNx4/

Please use .on if you are using jq1.7 et al.

Behaviour: When you type anything or paste anything on the 1st textarea the teaxtarea below captures the cahnge.

Rest I hope it helps the cause. :)

Helpful link =>

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

Catch paste input

EDIT:
Events list within .on() should be space-separated. Refer https://api.jquery.com/on/

code

$(document).ready(function() {
    var $editor    = $('#editor');
    var $clipboard = $('<textarea />').insertAfter($editor);
  
    if(!document.execCommand('StyleWithCSS', false, false)) {
        document.execCommand('UseCSS', false, true);
    }
        
    $editor.on('paste keydown', function() {
        var $self = $(this);            
        setTimeout(function(){ 
            var $content = $self.html();             
            $clipboard.val($content);
        },100);
     });
});
like image 22
Tats_innit Avatar answered Oct 12 '22 11:10

Tats_innit


I recently needed to accomplish something similar to this. I used the following design to access the paste element and value. jsFiddle demo

$('body').on('paste', 'input, textarea', function (e)
{
    setTimeout(function ()
    {
        //currentTarget added in jQuery 1.3
        alert($(e.currentTarget).val());
        //do stuff
    },0);
});
like image 11
Kevin Avatar answered Oct 12 '22 11:10

Kevin


Another approach: That input event will catch also the paste event.

$('textarea').bind('input', function () {
    setTimeout(function () { 
        console.log('input event handled including paste event');
    }, 0);
});
like image 7
Shahar Shokrani Avatar answered Oct 12 '22 12:10

Shahar Shokrani