jQuery Multiple Event Handling Hack
...this solution sucks, and leads to unnecessary code duplication!
by icampbell2
HTML
<input type="text" id="textField" />
<input type="button" onclick="setFocus();" value="click here" />
<ol>
<li>Type some text into the textfield.</li>
<li>Click the button.</li>
<li>Click out of the textfield, or
<br />
press enter, or
<br />
press tab to trigger an event.
</li>
</ol>
JavaScript
function setFocus() {
$("#textField").focus();
$("#textField").select();
var count = 1;
// when clicking away:
$("#textField").on("focusout keydown", function(e) {
var code = e.keyCode ? e.keyCode : e.which;
// if the key is NOT the enter or tab keys, which also trigger focusout:
if (code !== 13 && code !== 9) {
alert(e.type + ": " + count++);
}
$("#textField").off("focusout keydown");
});
// when hitting enter, or tabbing away:
$("#textField").on("keydown", function (e) {
var code = e.keyCode ? e.keyCode : e.which;
// if the key pressed is the enter or tab key:
if (code === 13 || code === 9) {
alert(e.type + ": " + count++);
}
$("#textField").off("keydown");
});
}