Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a custom onEnter event in jQuery?

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
});
like image 500
Ovesh Avatar asked Nov 28 '10 14:11

Ovesh


1 Answers

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.

like image 181
Nick Craver Avatar answered Sep 26 '22 20:09

Nick Craver