开发者

event.originalEvent undefined in focus event with jQuery autocomplete

I need to override the autocomplete focus event with a custom action and do something based on whether the user was selecting from the list using the keyboard and not the mouse. To d开发者_运维技巧o that I'm checking the originalEvent.type in the event object which is supposed to contain the type of action performed (keydown, keyup, mouseenter, etc).

However, the originalEvent object seems to be undefined, and I can't understand why. It is working just fine in the actual focus event in the autocomplete code, but not when I override that event inside of the autocomplete object.

Please see my code below. I'd appreciate any help on this as it's driving me bananas.

$( "#tags" ).autocomplete({
    source: availableTags,
    focus: function(event, ui) {
        //Check whether focus was triggered by a mouse or keyboard event
        if ( /^key/.test(event.originalEvent.type) ) {
            //Do something here
        }                   

        return false;
    }
});


I was actually able to get to originalEvent, but I don't think it helps you even if you can retrieve it; look at the console in the following example: http://jsfiddle.net/andrewwhitaker/DkumP/1/

You'll notice that the type of originalEvent is menufocus, which I don't think is what you were expecting.

A possible way to accomplish what you're trying to do is examine event.which, and see if it is the up arrow or down arrow (assuming those are the only keys you can use in the autocomplete widget):

$("input").autocomplete({
    source: /*...*/,
    focus: function(event, ui) {
        /* If the key that triggered this event is up or down arrow: */
        if (event.which === 38 || event.which === 40) {
            console.log('key');
        }
        else {
            console.log('mouse');
        }
    }
});

Here's an example: http://jsfiddle.net/andrewwhitaker/DkumP/2/


Thanks for the suggestion, Andrew.

I forgot to mention that I was using jQuery UI 1.8.5, so checking the "which" property didn't work for me either since it was undefined as well. Upgrading to 1.8.10 helped tho and it started working. Apparently, this whole thing was a bug in 1.8.5 which was fixed later on.

So in case anyone else is struggling with a similar issue - upgrade to the latest version, that should resolve it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜