$.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);
});
});
};
Call this plugin on an element, then you get callback events for before and after pasting:
$("#some-element").on("postpaste", function() {
// do something
}).pasteEvents();
The
$( .. )call is redundant here. As this function will be become a method of an jQuery object the context obviously already is a jQuery object, otherwise it wouldn’t have this method and returning it would not enable the chain-ability.Creating an jQuery object is only needed when dealing with a raw Element, such as in the callback of
$.each$("#some-element") .on("postpaste", function() { /* snip */ }).pasteEvents();Since it’s called right after another the order doesn’t really matter, but as a best practice it’s best to enable the events before binding them, instead of first binding them and then enabling them. So, something like this:
$("#some-element") .watchPasteEvents() .on("postpaste", function() { /* snip */ });$el.on("paste", function() { $el.trigger("prepaste"); setTimeout(function() { $el.trigger("postpaste"); }, delay); });This will potentially cause events to be triggered multiple times on the same element. This happens if the user has multiple jQuery collections that overlap (e.g.
$('.foo')and$('.bar')and some items haveclass="foo bar". This can be fixed by maintaining a boolean in the data object like this:$.fn.watchpasteEvents = function (delay) { delay = delay || 20; return this.each(function () { var $el = $(this); if ($el.data('pasteEventsBound')) { return true; } $el .data('pasteEventsBound', true) .on('paste', function () { $el.trigger('prepaste'); setTimeout(function () { $el.trigger('postpaste'); }, delay); }); }); };Thanks TeMc, this is a good improvement to my code!
What is the application of pasting event?
That code is Sweet !!!!!
@TC,
nice but ‘pasteEventsBound’ is added (and set to ‘true’) while its never been removed. So this works only once until page is refreshed.