I write the following code all the time to handle when the enter key pressed:
$("#selectorid").keypress(function (e) {
if (e.keyCode == 13) {
var targetType = e.originalTarget
? e.originalTarget.type.toLowerCase()
: e.srcElement.tagName.toLowerCase();
if (targetType != "textarea") {
e.preventDefault();
e.stopPropagation();
// code to handler enter key pressed
}
}
});
Is there a way to extend jQuery so that I could just write:
$("#selectorid").enterKeyPress(fn);
You can extend jquery something like:
jQuery.fn.returnPress = function(x) {
return this.each(function() {
jQuery(this).keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
x();
return false;
}
else {
return true;
}
});
});
};
Which can be invoked like:
$('selector').returnPress(function() { alert('enter pressed'); });
You can do what David G says, but perhaps the most correct way to approach this would be to write a custom event:
$(document).keypress(function(evt){
if(evt.keyCode==13) $(evt.target).trigger('enterPress');
});
Which could be bound like so:
$(document).bind('enterPress', fn);
See an example here: http://jquery.nodnod.net/cases/1821/run
The advantage to this approach is that you can bind, unbind, namespace, and trigger the event like any other event in jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With