How to create custom onEnter event in jQuery?

I would like to create a custom event in jQuery that captures ENTER onkeypress events, so I won’t need to code this path every time:

if(e.keyCode == 13) {
    // event code here
}

In other words, I would like to be able to code as follows:

$("selector").bind("enter", function(){
    // event code here
});
+5
source share
2 answers

Modern jQuery (1.7 and above) uses .on()event handlers to bind:

// 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 can have one .live()or .delegate()an event handler for all elements. Then use this to trigger a custom event, for example:

$(document.body).delegate(":input", "keyup", function(e) {
  if(e.which == 13)
    $(this).trigger("enter");
});

:input , :

$("selector").bind("enter", function(){
   //enter was pressed!
});

.

+10
$("selector").keyup(function (e) {
  if (e.keyCode == 13) {
    $(this).trigger("enter");
  }
}).bind("enter", function () {
  // event code here
});

, jQuery, . "enter" "enter.mywebapp" - . , .

+4

All Articles