Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created August 22, 2014 04:03
Show Gist options
  • Select an option

  • Save umidjons/e0a5b87543418f86c926 to your computer and use it in GitHub Desktop.

Select an option

Save umidjons/e0a5b87543418f86c926 to your computer and use it in GitHub Desktop.
Handle paste and drop events on jQuery

Handle paste and drop events on jQuery

Imagine we have .myinput input field, that we should process its value after text pasted into it. We can't access value in paste directly, so we should wait some time. For that purpose one can use setTimeout function. Here is example how to correctly handle paste event.

jQuery(document).ready(function($){
	$(".myinput").on("paste",function(){
		var _this=$(this);
		// we can access input value on paste after some time
		setTimeout(function(){
			// access element value
			console.log(_this.val());
		},1);
	});
});

Text/value can be pasted into input field via drag&drop. So we can also want to handle drop event. And when drop event fired we couldn't access its value directly too. Again we can use setTimeout.

jQuery(document).ready(function($){
	$(document).on("drop",function(e){
		var target=$(e.target);
		// drop acts as paste, but doesn't trigger paste event
		// and here too we can access text/value dropped into input after some time
		setTimeout(function(){
			// access element value
			console.log(target.val());
		},1);
	});

});

Note that, in the above code e.target is our input field. We can check it via $.is().

jQuery(document).ready(function($){
	$(document).on("drop",function(e){
		var target=$(e.target);
		if($(target).is('.myinput'))
  		// drop acts as paste, but doesn't trigger paste event
  		// and here too we can access text/value dropped into input after some time
  		setTimeout(function(){
  			// access element value
  			console.log(target.val());
  		},1);
	});

});
@everaldomatias
Copy link

Work fine!
Thanks!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment