Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way to extend jQuery to handle a custom enter key event?

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);
like image 781
Kenneth J Avatar asked Feb 03 '26 18:02

Kenneth J


2 Answers

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'); });
like image 103
David Glenn Avatar answered Feb 06 '26 08:02

David Glenn


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!