I would like to create a custom event in jQuery that captures ENTER onkeypress events, so that I would not have to code this way every time:
if(e.keyCode == 13) {
// event code here
}
In other words, I would like to be able to code like this:
$("selector").bind("enter", function(){
// event code here
});
Modern jQuery (1.7 and up) uses .on()
to bind event handlers:
// delegate binding - replaces .live() and .delegate()
$(document.body).on("keyup", ":input", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
// direct binding - analogous to .keyup()
$(":input").on("keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Older versions of jQuery use one of the following methods. You could have a single .live()
or .delegate()
event handler for all elements. Then use that to trigger your custom event, like this:
$(document.body).delegate(":input", "keyup", function(e) {
if(e.which == 13)
$(this).trigger("enter");
});
Not for any :input
element you could do exactly what you have:
$("selector").bind("enter", function(){
//enter was pressed!
});
You can test it out here.
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