I’ve been using a lot of jQuery lately to build web interfaces that react to user input. Part of the application I’m building makes heavy use of the keyup event to update a live preview of the app when a user enters text in an input element. This was sufficient for manually typing text and pasting from the clipboard using the standard keyboard shortcut (something I have always done), but today I was reminded that there are people out there who still cut & paste using their mouse and the built-in browser menus.
So this is when I turned to jQuery’s awesome paste event! Except it didn’t work as I expected it to. The event is fired before the input element’s value gets updated, presumably to allow the developer to do some validation of the current value and react accordingly. A simple timeout is all that’s needed to get the value pasted in the input. I needed to listen for these paste events in quite a few places and react to them after the input had been updated, so I wrote this awesome little plugin to make life easier:
$.fn.pasteEvents = function( delay ) {
if (delay == undefined) delay = 20;
return $(this).each(function() {
var $el = $(this);
$el.on("paste", function() {
$el.trigger("prepaste");
setTimeout(function() { $el.trigger("postpaste"); }, delay);
});
});
};
What does it do? Calling $.pasteEvents() on an element adds a tiny event handler that triggers a prepaste event before and postpaste event after a paste event occurs, making the task of handling paste events so much easier.
Now reacting to paste events is as simple as:
$("#some-element").on("postpaste", function() {
// do something
}).pasteEvents();
