This question is related to this one Autocomplete: first item focused only when the user type on tab key.
In order to make the first item focused only when the user type on tab key by using jqueryUi is possible to make something like this http://jsfiddle.net/uymYJ/8/ (1).
The bad thing about this implementation is the modification of the event object event.keyCode = $.ui.keyCode.DOWN;
.
In fact by doing this way, it will impact all other listeners on this event: all listener on the keydown event running later (which includes all delegated listeners) will see the event.keycode
as being $.ui.keyCode.ENTER
.
My questions are:
- Are my concerns about the modification of the event object justified? If not why?
- Can you suggest another way to achieve the same result?
- One opition, as suggested by @AaronDigulla, could be to use
document.createEvent()
. What is the proper way to use this method in this context? I did try the following code (3) but it does not work.
P.S.:
Here is the code about autocomplete (2).
(1)
$("#box").keydown(function(e){
if( e.keyCode != $.ui.keyCode.TAB) return;
e.keyCode = $.ui.keyCode.DOWN;
$(this).trigger(e);
e.keyCode = $.ui.keyCode.ENTER;
$(this).trigger(e);
$(this).siblings("input").select();
});
(2)
function (e) {
var f = typeof e == "string",
g = Array.prototype.slice.call(arguments, 1),
h = this;
return e = !f && g.length ? a.extend.apply(null, [!0, e].concat(g)) : e, f && e.charAt(0) === "_" ? h : (f ? this.each(function () {
var d = a.data(this, c),
f = d && a.isFunction(d[e]) ? d[e].apply(d, g) : d;
if (f !== d && f !== b) return h = f, !1
}) : this.each(function () {
var b = a.data(this, c);
b ? b.option(e || {})._init() : a.data(this, c, new d(e, this))
}), h)
}
(3)
$("#box").keydown(function(){
e = document.createEvent('KeyboardEvent');
e.initEvent("keydown", true, true);
$(this).dispatchEvent(e);
if( e.keyCode != $.ui.keyCode.TAB) return;
e.keyCode = $.ui.keyCode.DOWN;
$(this).trigger(e);
e.keyCode = $.ui.keyCode.ENTER;
$(this).trigger(e);
$(this).siblings("input").select();
});