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

I write the following code all the time to access when the enter key is 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 can simply write:

$("#selectorid").enterKeyPress(fn);
+3
source share
4 answers

You can extend jquery like this:

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;
      }
    });
  });
};

What can be called, for example:

$('selector').returnPress(function() { alert('enter pressed'); });
+5
source

You can do what David G says, but perhaps the best way to approach this would be to write a custom event:

$(document).keypress(function(evt){
    if(evt.keyCode==13) $(evt.target).trigger('enterPress');
});

What could be related like this:

$(document).bind('enterPress', fn);

See an example here: http://jquery.nodnod.net/cases/1821/run

, , , jQuery.

+4

, :

jQuery.fn.enterKeyPress = function(callback) {
  return this.not("textarea").keypress(function (e) {
    if (e.keyCode == 13) {
      callback($(this));
      return false;
    }
  });
};

:

$("input").enterKeyPress(function() { alert('hi'); });

<textarea>, , , keypress .

+2

, . , , submit, reset .

$.fn.focusNext = function(e) {
  var t = $(this);
  if ( t.is(":submit")==true || t.is(":reset")==true || t.is("textarea")==true || t.is("button")==true ) { exit(); }

  if (e.which==13 || e.which==3) {
    return this.each(function() {
      e.preventDefault();
      var fields = $(this).parents("form:eq(0)").find(":input:visible");
      var index = fields.index( this );
      if ( index > -1 && ( index + 1 ) < fields.length ) { fields.eq( index + 1 ).focus(); }
    });
  }
  return true;
};

,

$(":input").keypress(function(e) { $(this).focusNext(e); });

$(":input").live("keypress", function(e) { $(this).focusNext(e); });
0

Source: https://habr.com/ru/post/1738701/


All Articles