3

I need to change the standard behavior of the paste event. I'd like to delay the execution of the Paste event of few milliseconds. Is there any way to do that in pure javascript or with jQuery?

Edit: To be more precise, when a paste event is fired i need to make an action, wait few millis then paste.

elnabo
  • 264
  • 1
  • 2
  • 10
  • 1
    i suppose if you can detect it you can delay it :? http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/ – ajt Jun 03 '13 at 12:27
  • Do you want to delay the pasted text showing up, or when the event is triggered in JavaScript land? – alex Jun 03 '13 at 12:29
  • Well, i'd like to delay the pasted text showing up few milliseconds after the paste event being triggered, since you can't manually trigger a paste event. – elnabo Jun 03 '13 at 12:30

3 Answers3

0

You can add an onpaste event handler to the element receiving the paste event.

In the handler you should:

  1. Add a delay (there are multiple ways to do this)
  2. Return true so the default handler continues with the pasting operation.

For example:

var myElement = document.getElementById('pasteElement');

myElement.onpaste = function(e) {  //Add handler to onpaste event

  doSomethingHere();  //Do something before the delay

  sleep(200);  //Add the delay
  return true; //return true continue with default paste event
}

//One way to introduce a delay
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

EDIT: Added a line to show where to perform the action before the wait.

Sctt
  • 1
  • 1
0

How about just changing the color. The text remain white for 500 milliseconds.

$('input').each(function(){

   $(this).bind('paste', function(e){ 
   $(this).css('color', '#fff');
   setTimeout(function(){
  e.target.style.color="#000";
   },500)});
});
vusan
  • 5,221
  • 4
  • 46
  • 81
  • That would make all the text invisible, not only the pasted. Plus what i need is a true delay. Make an action then wait few millis then paste. – elnabo Jun 03 '13 at 13:03
  • I also wonder as the `setTimeout` function don't make us wait for the text display. – vusan Jun 03 '13 at 13:05
0

Building on Sctt's answer (but without the horrible sleep() function) try the following:

var delayTime = 5000; // 5 seconds

$('#myObject').bind('paste', function() {
  // Code here is executed before the delay

  setTimeout(function() {
    // Code here is executed during the delay
  }, delayTime);

  return true;
});
MTCoster
  • 5,868
  • 3
  • 28
  • 49