Skip to content

Instantly share code, notes, and snippets.

@DIntriglia
Last active June 25, 2022 16:30
Show Gist options
  • Save DIntriglia/27d8eca580e29d3086f716ed6ba1c6f2 to your computer and use it in GitHub Desktop.
Save DIntriglia/27d8eca580e29d3086f716ed6ba1c6f2 to your computer and use it in GitHub Desktop.
jquery .on('donetyping;, callback) integration
// $('#element').on('donetyping', callback)
// Fires donetyping event when a user has finished typing. This is determined by the time elapsed
// since the last keystroke and timeout parameter or the blur event--whichever comes first.
// @callback: function to be called when even triggers
// @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not
// caused by blur.
// Requires jQuery 1.7+
// Based on the jQuery extension created by @brad-christie on StackOverflow
//
$(":input").each(function () {
var timeout = 1e3, // 1 second timeout
timeoutReference,
doneTyping = function (el) {
if (!timeoutReference) return;
clearTimeout(timeoutReference);
timeoutReference = null;
el.trigger("donetyping");
},
$el = $(this);
// Chrome Fix (Use keyup over keypress to detect backspace)
// thank you @palerdot
$el.is(":input") &&
$el
.off(
"keyup.donetyping_handler keypress.donetyping_handler paste.donetyping_handler"
)
.on(
"keyup.donetyping_handler keypress.donetyping_handler paste.donetyping_handler",
function (e) {
// This catches the backspace button in chrome, but also prevents
// the event from triggering too preemptively. Without this line,
// using tab/shift+tab will make the focused element fire the callback.
if (e.type == "keyup" && e.keyCode != 8) return;
//Enter handling; Enter also causes a blur, so ignore the regular event
if (e.type == "keypress" && e.keyCode === 13) return;
// Check if timeout has been set. If it has, "reset" the clock and
// start over again.
if (timeoutReference) {
clearTimeout(timeoutReference);
timeoutHandle = null;
}
timeoutReference = setTimeout(function () {
// if we made it here, our timeout has elapsed. Fire the
// callback
doneTyping($el);
}, timeout);
}
)
.off("blur.donetyping_handler")
.on("blur.donetyping_handler", function () {
// If we can, fire the event since we're leaving the field
doneTyping($el);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment