Differentiate between focus event triggered by keyboard/mouse

The only way I can think of doing this is to have a handler listen in on the keypress and click events, and toggle a boolean flag on/off. Then on the focus handler of your input, you can just check what the value of your flag is, and go from there.

Probably something like

var isClick;
$(document).bind('click', function() { isClick = true; })
           .bind('keypress', function() { isClick = false; })
           ;

var focusHandler = function () {
    if (isClick) {
        // clicky!
    } else {
        // tabby!
    }
}

$('input').focus(function() {
    // we set a small timeout to let the click / keypress event to trigger
    // and update our boolean
    setTimeout(focusHandler,100);
});

Whipped up a small working prototype on jsFiddle (don’t you just love this site?). Check it out if you want.

Of course, this is all running off a focus event on an <input>, but the focus handler on the autocomplete works in the same way.

The setTimeout will introduce a bit of lag, but at 100ms, it might be negligible, based on your needs.

Leave a Comment