jQuery Tab and Enter Events

by Gust van de Wal

HTML

<input id="one" />
<input id="two" />
<p>
  Press Enter or Tab inside the first input to trigger events
</p>

CSS

body{
  margin: 0;
  padding: 10px;
  font: 16px sans-serif;
}

input{
  display: block;
  float: left;
  padding: 8px 6px;
  margin: 10px;
}

p{
  float: left;
  width: 100%;
  margin: 10px;
}

JavaScript

;(function () {
  $('body').on('keydown', 'input', function(e) {
    switch (e.which) {
      case 9:
        $(e.target).trigger('tab')
        break
      case 13:
        $(e.target).trigger('enter')
        break
      default:
        break
    }
  })
  $.fn.tab   = function(selector, data, fn) { return this.on('tab',   selector, data, fn) }
  $.fn.enter = function(selector, data, fn) { return this.on('enter', selector, data, fn) }
})()

$('#one').on('tab', function(e) {
  alert('Tab')
})
$('#one').on('enter', function(e) {
  alert('Enter')
})