user370306
user370306

Reputation:

Detect pasted text with Ctrl+v or right click -> paste

Using JavaScript how do you to detect what text the user pastes into a textarea?

Upvotes: 30

Views: 62050

Answers (8)

MD SHAYON
MD SHAYON

Reputation: 8063

The input event fires when the value of an , , or element has been changed.

const element = document.getElementById("input_element_id");
element.addEventListener('input', e => {
// insertText or insertFromPaste
   if(inputType === "insertFromPaste"){
       console.log("This text is copied");
   }
   if(inputType === "insertText"){
       console.log("This text is typed");
   }


})

Upvotes: -1

Willem Mulder
Willem Mulder

Reputation: 14014

Quite an old thread, but you might now use https://willemmulder.github.io/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.

Upvotes: 4

csandreas1
csandreas1

Reputation: 2388

You could either use html5 oninput attribute or jquery input event

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  $("body").on('input','#myinp',function(){
 $("span").css("display", "inline").fadeOut(2000);
  });
</script>
<style>
span {
  display: none;
}
</style>
</head>
<body>

<input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">

<span>Nice to meet you!</span>

</body>
</html>

Upvotes: -1

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93521

HTML5 already provides onpaste not only <input/> , but also editable elements (<p contenteditable="true" />, ...)

<input type="text" onpaste="myFunction()" value="Paste something in here">

More info here

Upvotes: 19

Michael
Michael

Reputation: 1203

I like the suggestion for the right click

$("#message").on('keyup contextmenu input', function(event) { 
  alert("ok");
});

finded here:

Source: Fire event with right mouse click and Paste

Upvotes: 1

Calixto
Calixto

Reputation: 426

Works on IE 8 - 10

Creating custom code to enable the Paste command requires several steps.

  1. Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.
  2. Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.
  3. Specify a data format in which to paste the selection through the getData method of the clipboardData object.
  4. invoke the method in the onpaste event to execute custom paste code.

To invoke this event, do one of the following:

  • Right-click to display the shortcut menu and select Paste.
  • Or press CTRL+V.

Examples

<HEAD>
<SCRIPT>
var sNewString = "new content associated with this object";
var sSave = "";
// Selects the text that is to be cut.
function fnLoad() {
    var r = document.body.createTextRange();
    r.findText(oSource.innerText);
    r.select();
}
// Stores the text of the SPAN in a variable that is set 
// to an empty string in the variable declaration above.
function fnBeforeCut() {
    sSave = oSource.innerText;
    event.returnValue = false;
}
// Associates the variable sNewString with the text being cut.
function fnCut() {
    window.clipboardData.setData("Text", sNewString);
}
function fnBeforePaste() {
    event.returnValue = false;
}
// The second parameter set in getData causes sNewString 
// to be pasted into the text input. Passing no second
// parameter causes the SPAN text to be pasted instead.
function fnPaste() {
    event.returnValue = false;
    oTarget.value = window.clipboardData.getData("Text", sNewString);
}
</SCRIPT>
</HEAD>
<BODY onload="fnLoad()">
<SPAN ID="oSource" 
      onbeforecut="fnBeforeCut()" 
      oncut="fnCut()">Cut this Text</SPAN>
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
      onbeforepaste="fnBeforePaste()" 
      onpaste="fnPaste()">
</BODY>

Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx

Upvotes: 1

Tim Down
Tim Down

Reputation: 324707

You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?

function getTextAreaSelection(textarea) {
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
        var sel = getTextAreaSelection(textarea);
        var initialLength = textarea.value.length;
        window.setTimeout(function() {
            var val = textarea.value;
            var pastedTextLength = val.length - (initialLength - sel.length);
            var end = sel.start + pastedTextLength;
            callback({
                start: sel.start,
                end: end,
                length: pastedTextLength,
                text: val.slice(sel.start, end)
            });
        }, 1);
    };
}

var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
    alert(pasteInfo.text);
    // pasteInfo also has properties for the start and end character
    // index and length of the pasted text
});

Upvotes: 23

Salil
Salil

Reputation: 47532

Following may help you

  function submitenter(myfield,e)
  {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == //event code of ctrl-v)
    {
      //some code here
    }

  }

  <teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea> 

Upvotes: 0

Related Questions