Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  174] [ 7]  / answers: 1 / hits: 21376  / 13 Years ago, wed, april 13, 2011, 12:00:00

I'm using jquery ui autocomplete and want to decipher between focus events triggered by keyboard interaction and mouse interaction. How would I go about this?



$('input').autocomplete({
source: function(request, response) {
...
},
focus: function(event, ui) {
// If focus triggered by keyboard interaction
alert('do something');
// If focus event triggered by mouse interaction
alert('do something else');
}
});


Thanks


More From » jquery

 Answers
1

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.


[#92747] Tuesday, April 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malkajillc

Total Points: 652
Total Questions: 107
Total Answers: 98

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
malkajillc questions
;