Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:</p> <pre><code>$('#myInput').keydown(function(ev) { if (ev.which == 13) { ev.preventDefault(); // Do some stuff that handles the enter key } }); </code></pre> <p>I want to abbreviate it to this:</p> <pre><code>$('#myInput').enterKey(function() { // Do some stuff that handles the enter key }); </code></pre> <p>trigger and bind don't tell the whole story - this is a JQuery plugin. <a href="http://docs.jquery.com/Plugins/Authoring" rel="nofollow noreferrer">http://docs.jquery.com/Plugins/Authoring</a></p> <p>The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:</p> <pre><code>(function($){ $('body').on('keydown', 'input', function(ev) { if (ev.which == 13) { var enterEv = $.extend({}, ev, { type: 'enterKey' }); return $(ev.target).trigger(enterEv); } }); $.fn.enterKey = function(selector, data, fn) { return this.on('enterKey', selector, data, fn); }; })(jQuery); </code></pre> <p><a href="http://jsfiddle.net/b9chris/CkvuJ/4/" rel="nofollow noreferrer">http://jsfiddle.net/b9chris/CkvuJ/4/</a></p> <p>A nicety of the above is you can handle keyboard input gracefully on link listeners like:</p> <pre><code>$('a.button').on('click enterKey', function(ev) { ev.preventDefault(); ... }); </code></pre> <p>Edits: Updated to properly pass the right <code>this</code> context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.</p> <p>Old jsfiddle: <a href="http://jsfiddle.net/b9chris/VwEb9/24/" rel="nofollow noreferrer">http://jsfiddle.net/b9chris/VwEb9/24/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload